Home >Web Front-end >JS Tutorial >How to Insert Elements After Other Elements in JavaScript?
Inserting Elements After Others in JavaScript
Inserting elements after existing nodes is a common operation in JavaScript. However, while there's the insertBefore() method, it can only add elements before a reference node. To insert elements after, we need an alternative approach.
Solution without Libraries
To insert an element after another without using libraries, we can use the following code:
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Here's a breakdown:
If referenceNode is the last child, the nextSibling will be null. insertBefore handles this case by adding the new node to the end of the list.
Reusable Function
We can wrap this functionality in a reusable function:
function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); }
Example
To test this function, we can use the following snippet:
function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } var el = document.createElement("span"); el.innerHTML = "test"; var div = document.getElementById("foo"); insertAfter(div, el);
This will create a new span element with the text "test" and insert it after the div element with the ID "foo."
The above is the detailed content of How to Insert Elements After Other Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!