JS DOM: Insert adjacent element

By Xah Lee. Date: . Last updated: .
target.insertAdjacentElement(position, new_elm)

Move a element and insert it adjacent to target node's begin/end tags.

Return the element inserted, or null if failed.

position is a string, and must be one of:

"beforebegin"
Before the beginning tag. (as previous sibling.)
"afterbegin"
After the beginning tag. (as first child.)
"beforeend"
Before end tag . (as last child).
"afterend"
After the tag. (as next sibling.)

🆕 supported by browsers since 2019.

🛑 WARNING: If the node to be inserted already exists in the same doc, it is removed from the original place and moved to the new place.

// create new node p
const xnew = document.createElement("p");

// add text content hello
xnew.textContent = "hello";

// pick an existing node
const xtarget = document.getElementsByTagName("p")[0];

// insert after
xtarget.insertAdjacentElement("afterend", xnew);