Insert an element after other one
Place an element right after a reference element.
function insertAfter(element, reference) { reference.after(element); }
Usage
Markup
<ol id="steps"><li id="one">One</li><li id="three">Three</li></ol>
Script
const two = document.createElement('li');
two.textContent = 'Two';
insertAfter(two, document.querySelector('#one'));
[...document.querySelector('#steps').children].map(li => li.textContent); // → ['One', 'Two', 'Three']
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.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.