There are a few ways to add an HTML element / code inside, outside, before, or after an element. One is with the insertAdjacentHTML
method. With it you can use HTML code, without the need of createElement
.
element.insertAdjacentHTML("posição", "código-html");
To control where you want the element, simply add one of the values below instead of position
Beforebegin: Before Element
afterbegin: Inside the element and before your first child
beforeend: Inside the element and after your last child
afterend: After the
Example:
var t = document.querySelector("#t");
t.insertAdjacentHTML('beforebegin', '<div class="verde"></div>');
#t{
width: 300px;
background: red;
height: 300px;
}
.verde{
background: green;
width: 30px;
height: 30px;
display: block;
}
.roxo{
background: purple;
width: 30px;
height: 30px;
display: block;
}
<div id="t">
<div class="roxo"></div>
</div>