# Insert an element before other one

Place an element right before a reference element.

Canonical: https://1loc.dev/dom/insert-an-element-before-other-one/
Version: 1.0.0
Runtime: JavaScript · modern browsers (DOM)
Verification: Usage lines executed in headless Chromium against the fixture markup; no external services
Updated: 2026-10-28

## Implementation

```javascript
function insertBefore(element, reference) { reference.before(element); }
```

## Usage

Markup:

```html
<ol id="steps"><li id="two">Two</li></ol>
```

Script:

```javascript
const one = document.createElement('li');
one.textContent = 'One';
insertBefore(one, document.querySelector('#two'));
[...document.querySelector('#steps').children].map(li => li.textContent); // → ['One', 'Two']
```

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- before also accepts several nodes, and strings, which it inserts as text.
- Inserting a node that is already in the document moves it.

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/insert-an-element-before-other-one.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Uses Element.before. Executed in Chromium. Original MDX retained as inert source evidence.
