Insert given HTML after an element
Parse an HTML string and insert it after the element.
function insertHtmlAfter(html, element) { element.insertAdjacentHTML('afterend', html); }
Usage
Markup
<p id="intro">Intro</p>
Script
insertHtmlAfter('<p>After</p>', document.querySelector('#intro'));
document.querySelector('#intro').nextElementSibling.textContent; // → 'After'
Know the limits
- The string is parsed as HTML: never pass user input, or an attacker can inject markup and event handlers (XSS). For untrusted text, use insertAdjacentText or create elements.
- Unlike innerHTML +=, it does not re-parse the existing content, so listeners and state stay intact.
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 given HTML after an element from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Documented as a reference with executed usage lines. 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.