How to Insert an Element After Another Element in JavaScript
For inserting an element after another element in JavaScript can be done in some ways. Let’s see which are they and try examples.
To insert an element after another element you should use the insertBefore() method. Here is the syntax:
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Here referenceNode is the node that you want to put after newNode. If the referenceNode is the last child, the referenceNode.nextSibling will be null and insertBefore can handle the case by adding to the end of the list:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<style>
#divId {
color: green;
font-size: 25px;
}
span {
color: blue;
font-size: 20px;
}
</style>
</head>
<body>
<div id="divId">Welcome to W3docs</div>
<script>
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
let elem = document.createElement("span");
elem.innerHTML = "It's a Javascript book";
let div = document.getElementById("divId");
insertAfter(div, elem);
</script>
</body>
</html>
You can also use one of the newest approaches: the insertAdjacentElement() method which inserts a given element node at a specified position relative to the element it is executed upon:
<!-- refElement.insertAdjacentElement('beforebegin', moveMeElement); -->
<p id="refElement">
<!-- refElement.insertAdjacentElement('afterbegin', moveMeElement); -->
... content ...
<!-- refElement.insertAdjacentElement('beforeend', moveMeElement); -->
</p>
<!-- refElement.insertAdjacentElement('afterend', moveMeElement); -->
The insertBefore() Method
The Node.insertBefore() method is used to insert a node before a reference node as parent node's child. If the specified node exists in the document, insertBefore() moves it from its current position to the new position, meaning that a node cannot be in two locations of the document at the same time.