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.

const xb = document.getElementById("x-b");
const xc = document.getElementById("x-c");

// moved xb to before xc
xc.before(xb);
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 children.
  • nodes can be a string. if so, it creates a text node.
  • nodes can be many, comma separated.

🆕 supported by browsers since 2019.

target.append(nodes, etc)
  • Insert as last children.
  • 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.