Insert given HTML after an element

Parse an HTML string and insert it after the element.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

insert-given-html-after-an-element.js
function insertHtmlAfter(html, element) { element.insertAdjacentHTML('afterend', html); }

Usage

Markup

fixture.html
<p id="intro">Intro</p>

Script

usage.js
insertHtmlAfter('<p>After</p>', document.querySelector('#intro'));
document.querySelector('#intro').nextElementSibling.textContent; // → 'After'

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

  • 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.

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”.