JS: insertAdjacentElement

By Xah Lee. Date: . Last updated: .

insertAdjacentElement lets you insert an element before or after a given element as sibling, or, as first child or last child.

node.insertAdjacentElement(position, newNode)
Move a element and insert it adjacent to 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.)
// create new node p containing hi
const y = document.createElement("p");
y.textContent = "hi";

// a existing node
const x = document.getElementsByTagName ("p")[0] ;

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