Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Node.insertBefore — inserting before a child

Node.insertBefore inserts or moves a node before a specified child. Passing null inserts it at the end.

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

parent.insertBefore(node, child)

Call Node.insertBefore on the parent: parent.insertBefore(node, child). child must be its direct child or null (append). Supply both arguments. The method returns node.

An existing node is moved, not copied. For a DocumentFragment, its children are inserted; the returned fragment is empty.

An invalid hierarchy, such as a cycle, causes HierarchyRequestError. The method checks for a cycle before checking whether child belongs to the parent. If insertion would create a cycle, it throws HierarchyRequestError even if child does not belong to the parent. If the earlier checks pass, a non-null child that is not a direct child of the parent causes NotFoundError. This is a DOM API, not ECMAScript; Node.js 24 alone does not establish DOM availability.

Examples

const parent = document.createElement('div');
const a = document.createTextNode('A');
const b = document.createTextNode('B');
parent.insertBefore(b, null);
const returned = parent.insertBefore(a, b);
console.log(parent.textContent);
console.log(returned === a);
parent.insertBefore(b, a);
console.log(parent.textContent);

Result

AB
true
BA

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources