Element

Element.prototype.before

Inserts a set of Node or string objects in the children list of this Element's parent, just before this Element

Syntax

JavaScript
element.before(...nodes)

Parameters

ParameterTypeDescription
nodes...(Node | string)[]Nodes or strings to insert

Return Value

undefined

Examples

Basic Usage
const ref = document.querySelector('.content')!
const heading = document.createElement('h2')
heading.textContent = 'Section Title'
ref.before(heading)
Practical Example
const target = document.getElementById('main')!
target.before('Before content ', document.createElement('hr'))
Advanced Usage
const item = document.querySelector('.list-item:nth-child(3)')!
const newItem = document.createElement('div')
newItem.textContent = 'Inserted before third'
item.before(newItem)

Understanding Element.prototype.before

The Element.prototype.before method in JavaScript inserts a set of Node or string objects in the children list of this Element's parent, just before this Element. 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.before(...nodes). It accepts 1 parameter: nodes. When called, it returns undefined. Understanding when and how to use before() helps you write more expressive, readable code.

Common use cases for Element.prototype.before include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-after, dom-prepend, dom-insertbefore, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for Element.prototype.before 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.