DOM: Insert After a Element

By Xah Lee. Date: . Last updated: .

The Problem

In JavaScript/DOM, there's the method “insertBefore”. But what if you want to insert after a element?

Solution

Use:

x.insertAdjacentElement(position, newEle)

position is one of:

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

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

// insert after
x.insertAdjacentElement("afterend", y);

Solution 2, using insertBefore

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's 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.comstackoverflow.com

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon