Replace an element
Swap an element for another in the same position.
function replace(element, replacement) { element.replaceWith(replacement); }
Usage
Markup
<div id="slot"><p id="loading">Loading…</p></div>
Script
const ready = document.createElement('p');
ready.textContent = 'Ready';
replace(document.querySelector('#loading'), ready);
document.querySelector('#slot').textContent; // → 'Ready'
Know the limits
- Element.replaceWith is the modern form of parentNode.replaceChild(newNode, oldNode), whose argument order is easy to swap by mistake.
- Listeners on the old element are not transferred.
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 Replace an element from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses Element.replaceWith. 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.