Replace an element

Swap an element for another in the same position.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

replace-an-element.js
function replace(element, replacement) { element.replaceWith(replacement); }

Usage

Markup

fixture.html
<div id="slot"><p id="loading">Loading…</p></div>

Script

usage.js
const ready = document.createElement('p');
ready.textContent = 'Ready';
replace(document.querySelector('#loading'), ready);
document.querySelector('#slot').textContent; // → 'Ready'

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

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

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