Categories
JavaScript Answers

How to append child after element with JavaScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.