JS DOM: Insert Element

By Xah Lee. Date: . Last updated: .

🛑 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.

Insert before, insert after

target.before(nodes, etc)
  • Insert nodes before target node.
  • nodes can be a string. if so, it creates a text node.
  • nodes can be many, comma separated.

⭐ supported by browsers since 2019.

// create a paragraph element and insert it before first element child of body
const xnew = document.createElement("p");
xnew.setAttribute("id", "YfqzT");
xnew.textContent = "good morn";
document.body.firstElementChild.before(xnew);
target.after(nodes, etc)
  • Insert nodes after target node.
  • nodes can be a string. if so, it creates a text node.
  • nodes can be many, comma separated.

⭐ supported by browsers since 2019.

Insert before or after or as first child or last child

target.insertAdjacentElement(position, new_elm)

Insert as child

target.prepend(nodes, etc)
  • Insert as first child.
  • nodes can be a string. if so, it creates a text node.
  • nodes can be many, comma separated.

⭐ supported by browsers since 2019.

// create a paragraph element and insert it as first node of body
const xnew = document.createElement("p");
xnew.setAttribute("id", "WkHwq");
xnew.textContent = "good eve";
document.body.prepend(xnew);
target.append(nodes, etc)
  • Insert as last child.
  • nodes can be a string. if so, it creates a text node.
  • nodes can be many, comma separated.

⭐ supported by browsers since 2019.

Old methods

as last child

target.appendChild(new_node)

before a child

target_parent.insertBefore(new_node, target) 👎
  • Inserts new_node before target.
  • but you need to get target's parent in order to call. e.g. target.parentNode.