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.
Checkout more articles on JavaScript
Syntax
The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.
1 | referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <html> <head> <title>How to insert an element after another element in JavaScript - Clue Mediator</title> </head> <body> <span id="refElementId">Clue</span> <script> function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } var el = document.createElement("span"); el.innerHTML = "Mediator"; el.style = "margin-left: 5px"; var div = document.getElementById("refElementId"); insertAfter(div, el); </script> </body> </html> |
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..!! 🙂