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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *