Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Element.replaceChildren() — replacing all children

Element.replaceChildren() replaces an element's children with node and string arguments. Calling it without arguments removes all children.

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.replaceChildren(...nodes)

Element.replaceChildren comes from the DOM standard's ParentNode mixin, not ECMAScript. It replaces every child of an element, leaving the element itself intact. It returns undefined.

Arguments are nodes or strings and are processed in the order supplied. Strings become Text nodes, not parsed HTML. Existing nodes are moved, not cloned. Passing the same node again moves it rather than adding another child. If a and b are distinct elements, element.replaceChildren(a, b, a) leaves b followed by a. element.replaceChildren() removes all children.

An invalid hierarchy, such as inserting an element into itself, throws a DOMException named HierarchyRequestError.

This is a browser DOM API; having Node 24 does not prove availability. Check typeof Element !== 'undefined' && typeof Element.prototype.replaceChildren === 'function' in the target environment.

Examples

const box = document.createElement('div');
box.textContent = 'Old';
const label = document.createElement('strong');
label.textContent = 'New';

box.replaceChildren('Status: ', label);
console.log(box.textContent);
console.log(box.childNodes.length);
console.log(box.lastChild === label);

box.replaceChildren();
console.log(box.childNodes.length);

Result

Status: New
2
true
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources