Home >Web Front-end >JS Tutorial >How to Insert an Element After Another in JavaScript?
Inserting an Element After Another in JavaScript
While JavaScript provides the insertBefore() method to insert an element before another, there is no built-in method for inserting an element after another. To achieve this, we can utilize the following custom technique:
Solution:
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Explanation:
insertBefore() takes two arguments: the new node to insert and the node before which the new node should be placed. By passing in referenceNode.nextSibling, we ensure that the new node is inserted after the reference node.
Example Function:
function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); }
Usage:
var el = document.createElement("span"); el.innerHTML = "test"; var div = document.getElementById("foo"); insertAfter(div, el);
This will insert a span element with the text "test" after the div element with the id "foo".
The above is the detailed content of How to Insert an Element After Another in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!