JavaScript: 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);
BUY
ΣJS
JavaScript in Depth

DOM Scripting

Overview

DOM Methods

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc