CKTIS / JavaScript
Element.replaceWith — replacing an element
Element.replaceWith replaces an element within its parent with nodes and text. Strings become text rather than HTML markup.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
element.replaceWith(...nodes)Element.replaceWith comes from the DOM standard’s ChildNode mixin, not an ECMAScript edition. Calling element.replaceWith(...nodes) replaces the element itself, not its children; replaceChildren(...nodes) changes children.
Arguments are nodes and strings, in order. Nodes are moved, not copied; strings create Text nodes without HTML parsing. The method returns undefined. Calling it without arguments removes the element; without a parent, it makes no changes.
An invalid tree structure can cause HierarchyRequestError. Check availability with typeof Element.prototype.replaceWith === 'function' in a DOM environment; the Node.js version alone does not establish support.
Examples
const container = document.createElement('div');
const oldElement = document.createElement('span');
oldElement.textContent = 'old';
container.appendChild(oldElement);
const replacement = document.createElement('strong');
replacement.textContent = 'new';
const result = oldElement.replaceWith(replacement, ' <text>');
console.log(container.textContent);
console.log(container.firstChild === replacement);
console.log(oldElement.parentNode === null);
console.log(result === undefined);Result
new <text> true true true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.