CKTIS / JavaScript
Node.replaceChild — replacing a child
Node.replaceChild replaces a parent's direct child and returns the removed node. The replacement node is the first argument.
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
const removedNode = parent.replaceChild(newChild, oldChild);parent.replaceChild(newChild, oldChild) replaces oldChild with newChild and returns oldChild. Arguments must be nodes, not strings. This is a DOM API, not an ECMAScript feature.
An existing newChild is moved, not copied. A DocumentFragment inserts its children rather than the fragment itself.
An invalid structure, such as a cycle, can cause HierarchyRequestError. The method checks whether the replacement would create a cycle before it checks whether oldChild is a direct child of parent. If the preceding checks pass and oldChild is not a direct child of parent, the method throws NotFoundError.
Examples
const parent = document.createElement('div');
const oldChild = document.createTextNode('old');
const newChild = document.createTextNode('new');
parent.appendChild(oldChild);
const removedNode = parent.replaceChild(newChild, oldChild);
console.log(parent.textContent);
console.log(removedNode === oldChild);
console.log(oldChild.parentNode === null);Result
new 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.