CKTIS / JavaScript
Element.before() — inserting before an element
Element.before() inserts nodes and text into the element’s parent, not into the element itself. They normally go before the reference element.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
element.before(...nodes)Element.before is a DOM method from the ChildNode mixin, not an ECMAScript function. element.before(...nodes) accepts nodes and strings; strings become Text nodes, not HTML.
Existing nodes move rather than being copied. If you pass the reference element itself as an argument, it can move too. If the parent of target is an Element or a DocumentFragment, target.before(target, 'x') puts the text after target, not before it. If target is the document element, the same call throws HierarchyRequestError: a fragment with a Text child cannot be inserted into a Document. On success, the method returns undefined.
An element without a parent remains unchanged; the parent need not belong to the document. Invalid hierarchy causes HierarchyRequestError. Unlike parent.insertBefore(node, element), you call this method on the reference element.
Examples
const parent = document.createElement('div');
const target = document.createElement('span');
target.textContent = 'B';
parent.appendChild(target);
const first = document.createElement('strong');
first.textContent = 'A';
const result = target.before(first, ' + ');
console.log(parent.textContent);
console.log(parent.firstChild === first);
console.log(result === undefined);Result
A + B true true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.