Insert an element before other one

Place an element right before a reference element.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

insert-an-element-before-other-one.js
function insertBefore(element, reference) { reference.before(element); }

Usage

Markup

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

Script

usage.js
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.

Know the 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 above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Insert an element before other one from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Uses Element.before. Executed in Chromium. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Usage lines executed in headless Chromium against the fixture markup; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.