There are a few ways to add an HTML element/code inside, outside, before or after an element. One of them is with the method insertAdjacentHTML
. With it you can use an HTML code, without the need createElement
.
element.insertAdjacentHTML("posição", "código-html");
To control where you want the element, simply add one of the values below in place of position
beforebegin: Before the Element
afterbegin: Inside the element and before your first child
beforeend: Inside the element and after your last child
afterend: After the element
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>
The prependChild method doesn’t exist, that’s what’s wrong.
– bfavaretto
How do I make it work?
– AKU