Home >Web Front-end >JS Tutorial >How to Insert an Element After Another in JavaScript Without Libraries?
Inserting Elements After Others in JavaScript Without a Library
In JavaScript, the insertBefore() method exists for inserting an element before a specified reference node. However, what if you want to insert an element after another element without relying on jQuery or other libraries?
Answer
The following snippet is what you need:
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
Here's how it works:
Example Code
To use this solution, you can define the following function:
function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); }
You can then use this function like so:
var el = document.createElement("span"); el.innerHTML = "test"; var div = document.getElementById("foo"); insertAfter(div, el);
This code will insert the span element with the text "test" after the div with the id "foo".
The above is the detailed content of How to Insert an Element After Another in JavaScript Without Libraries?. For more information, please follow other related articles on the PHP Chinese website!