Web APIs

Node.insertBefore()

Try the free JavaScript compiler

Insert a node immediately before a direct child. Passing null as the reference appends the node. Example console output: true.

Formal Syntax & Structure

javascript syntaxjavascript
parent.insertBefore(newNode, referenceNode)

Parameters & Attributes

NameTypeDescription
newNodeNodeNode to insert.
referenceNodeNode or nullExisting child or null.

Return Value

Node

The inserted node.

Working Example

Example Snippetjavascript
const root=document.createElement("div"); const a=document.createElement("a"),b=document.createElement("b"); root.append(b); root.insertBefore(a,b); console.log(root.firstChild===a);
JavaScript Reference