Element.prototype.insertBefore
Inserts a node before a reference node as a child of a specified parent node
Syntax
element.insertBefore(newNode, referenceNode)Parameters
| Parameter | Type | Description |
|---|---|---|
| newNode | Node | The node to insert |
| referenceNode | Node | null | The node before which newNode is inserted |
Return Value
The inserted node
Examples
const list = document.querySelector('ul')!
const newItem = document.createElement('li')
newItem.textContent = 'Inserted'
list.insertBefore(newItem, list.firstChild)function insertAt(parent: HTMLElement, child: HTMLElement, index: number) {
const ref = parent.children[index] || null
parent.insertBefore(child, ref)
}const container = document.getElementById('items')!
const divider = document.createElement('hr')
const thirdChild = container.children[2]
container.insertBefore(divider, thirdChild)Understanding Element.prototype.insertBefore
The Element.prototype.insertBefore method in JavaScript inserts a node before a reference node as a child of a specified parent node. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.
The method signature is element.insertBefore(newNode, referenceNode). It accepts 2 parameters: newNode, referenceNode. When called, it returns the inserted node. Understanding when and how to use insertBefore() helps you write more expressive, readable code.
Common use cases for Element.prototype.insertBefore include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-appendchild, dom-before, dom-after, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.prototype.insertBefore is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Element.prototype.appendChildAdds a node to the end of the list of children of a specified parent node
Element.prototype.beforeInserts a set of Node or string objects in the children list of this Element's parent, just before this Element
Element.prototype.afterInserts a set of Node or string objects in the children list of this Element's parent, just after this Element
Element.prototype.prependInserts a set of Node objects or strings before the first child of the Element
More Element Methods
Other methods in the Element object
Related Tools
More Element Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.