Insert an element after other one

Place an element right after a reference element.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

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

Usage

Markup

fixture.html
<ol id="steps"><li id="one">One</li><li id="three">Three</li></ol>

Script

usage.js
const two = document.createElement('li');
two.textContent = 'Two';
insertAfter(two, document.querySelector('#one'));
[...document.querySelector('#steps').children].map(li => li.textContent); // → ['One', 'Two', 'Three']

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

  • Element.after, before and replaceWith are the modern ChildNode methods; the original used parentNode.insertBefore with nextSibling.
  • 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 after other one from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Uses Element.after. 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”.