Sometimes, we want to append child after element with JavaScript.
In this article, we’ll look at how to append child after element with JavaScript.
How to append child after element with JavaScript?
To append child after element with JavaScript, we can use the insertBefore method.
For instance, we write
if (parentGuest.nextSibling) {
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
} else {
parentGuest.parentNode.appendChild(childGuest);
}
to call parentGuest.parentNode.insertBefore to insert childGuest before parentGuest element’s next sibling to insert it after parentGuest if nextSibling exists.
Otherwise, we insert it as its last child with appendChild.
Conclusion
To append child after element with JavaScript, we can use the insertBefore method.