JS: Insert After an Element

By Xah Lee. Date: . Last updated: .

see JS: insertAdjacentElement

Insert After a Node, Solution Before Year 2011

Year 2011. Use the method insertBefore with a second parameter that point to a sibling node. Like this:

targetNode.parentNode.insertBefore(newNode, targetNode.nextSibling);

If next sibling doesn't exist, it would still work, because the targetNode.nextSibling will return β€œnull”, and JavaScript will just append to last child of parent node.

Here is a full example:

// create your new node <p>Hi</p>
const y = document.createElement("p");
 y.textContent = "Hi";

// a existing node
const x = document.getElementById("xyz");

// insert y before x
// x.parentNode.insertBefore(y, x);

// insert y after x
x.parentNode.insertBefore(y, x.nextSibling);

Note: when you create a node in DOM, it can exist only in one place. You can not insert it both before and after. If you want to insert the same node in multiple places, you can create a copy first by newNode.cloneNode(true).

Thanks to karim79 and Phrogz for helping on this question. stackoverflow.com β€’ stackoverflow.com