Element

Element.prototype.insertBefore

Inserts a node before a reference node as a child of a specified parent node

Syntax

JavaScript
element.insertBefore(newNode, referenceNode)

Parameters

ParameterTypeDescription
newNodeNodeThe node to insert
referenceNodeNode | nullThe node before which newNode is inserted

Return Value

The inserted node

Examples

Basic Usage
const list = document.querySelector('ul')!
const newItem = document.createElement('li')
newItem.textContent = 'Inserted'
list.insertBefore(newItem, list.firstChild)
Practical Example
function insertAt(parent: HTMLElement, child: HTMLElement, index: number) {
  const ref = parent.children[index] || null
  parent.insertBefore(child, ref)
}
Advanced Usage
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

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.