Sometimes, we want to prepend or append a child element in a parent element on our web page.
In this article, we’ll look at how to prepend and append an element with regular JavaScript.
Prepend an Element
We can prepend an element by using the insertBefore
method.
For instance, if we have the following HTML:
<div id='parent'>
<p>
hello world
</p>
</div>
Then we can prepend an element before the p
element in the div by writing:
const parent = document.getElementById("parent");
const child = document.createElement("div");
child.innerHTML = 'Are we there yet?';
parent.insertBefore(child, parent.firstChild);
We get the div with document.getElementById
.
Then we create a div with document.createElement
.
And then we add some content to the child
div by setting the innerHTML
property.
Finally, we call parent.insertBefore
with the child
element we want to insert and parent.firstChild
to prepend child
before the first child node of parent
.
Append an Element
We can append an element into a container element by using the appendChild
method.
For instance, if we have the following HTML:
<div id='parent'>
<p>
hello world
</p>
</div>
Then we can add a child after the p
element by writing:
const parent = document.getElementById("parent");
const child = document.createElement("div");
child.innerHTML = 'Are we there yet?';
parent.appendChild(child);
The first 3 lines are the same as the previous example.
The only difference is that we call parent.appendChild
with child
to add child
after the p
element.
Conclusion
We can use the insertBefore
method to prepend an element as the first child element.
And we can use the appendChild
method to add a child element as the last child of the parent element.