How to insert an element after another element in JavaScript

In this article, we will show you how to insert an element after another element in JavaScript. Here we will use only JavaScript method to insert an element. We can also do it using other libraries.

Syntax

The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.

Where referenceNode is the node you want to put newNode after. If referenceNode is the last child within its parent element, that’s fine, because referenceNode.nextSibling will be null and insertBefore handles that case by adding to the end of the list.

Example

In the above example, we are adding Mediator span after the Clue. So the output will be Clue Mediator.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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