Insert given HTML before an element
Parse an HTML string and insert it before the element.
function insertHtmlBefore(html, element) { element.insertAdjacentHTML('beforebegin', html); }
Usage
Markup
<p id="intro">Intro</p>
Script
insertHtmlBefore('<h2>Title</h2>', document.querySelector('#intro'));
document.querySelector('#intro').previousElementSibling.tagName; // → 'H2'
Know the limits
- The string is parsed as HTML: never pass user input (XSS). Inserted script elements do not run, but inline event handlers such as onerror do.
- The element needs a parent for beforebegin and afterend positions.
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 before 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.