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
- Methods of Promises in JavaScript
- console methods in JavaScript
- How to open an URL in a new tab using JavaScript
- How to copy text to the clipboard using JavaScript
Syntax
The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.
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
<title>How to insert an element after another element in JavaScript - Clue Mediator</title>
<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>
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..!! π