Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

Element.before() and after()

Reference for before() and after(): insert nodes or text as siblings directly before or after an element, with parentless behavior and moving rules.

before() inserts nodes or strings immediately before an element, and after() inserts them immediately after it. In both cases the new content becomes a sibling in the element's parent. They belong to the ChildNode interface, so they also work on text and comment nodes, and on DocumentType.

Strings become text nodes, never HTML.

JavaScript
heading.before(banner);
heading.after(intro, "Read on.");

Try it

Insert beside an element
Detached elements and moving

Syntax

JavaScript
node.before(...nodesOrStrings)
node.after(...nodesOrStrings)
Name Description
nodesOrStrings Zero or more Node objects or strings. Strings are inserted as Text nodes.

Return value: undefined.

Exceptions: a HierarchyRequestError DOMException if the result would be an invalid tree, for example inserting an element's own ancestor.

Usage notes

  • No parent, no effect. If the element has no parent, both methods silently do nothing. They never throw for that reason, so a detached element will quietly ignore the call.
  • Moves existing nodes. Passing a node that is already in the document removes it from its old position first.
  • Inserting itself is safe. If you pass the element or a node that is its own neighbor, the browser works out the correct final position, so a.before(a) leaves things unchanged.
  • Siblings, not children. To insert inside an element use append() and prepend().
  • Older equivalent. parent.insertBefore(newNode, reference) does the same as reference.before(newNode). After-insertion historically required insertBefore(newNode, reference.nextSibling).
  • Multiple items go in together, preserving the order of the arguments.
  • Strings are not parsed. For an HTML string beside an element use insertAdjacentHTML("beforebegin" | "afterend", html), with trusted input only.
  • Text nodes too. Because the methods are on ChildNode, textNode.after(element) works.

Browser support

Supported by all current browsers. Very old browsers lack these methods and only provide insertBefore().