DOM: Insert After a Element

By Xah Lee. Date: . Last updated: .
x.insertAdjacentElement(position, new_node)
inserts a element adjacent to x's begin/end tags.

position is one of:

"beforebegin"
Before the element itself.
"afterbegin"
Just inside the element, before its first child.
"beforeend"
Just inside the element, after its last child.
"afterend"
After the element itself.
// 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);

old Solution to Insert After a Node

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'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

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js