This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The replaceChild() method of the Node interface replaces a child node within the given (parent) node.
replaceChild(newChild, oldChild)
newChildThe new node to replace oldChild.
Warning: If the new node is already present somewhere else in the DOM, it is first removed from that position.
oldChildThe child to be replaced.
Note: The parameter order, new before old, is unusual. Element.replaceWith(), applying only to nodes that are elements, may be easier to read and use.
The replaced Node. This is the same node as oldChild.
HierarchyRequestError DOMException
Thrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs:
oldChild is not a Document, DocumentFragment, or an Element.oldChild by newChild would lead to a cycle, that is if newChild is an ancestor of the node.newChild is not a DocumentFragment, a DocumentType, an Element, or a CharacterData.Text, and its parent is a Document.DocumentType and its parent is not a Document, as a doctype should always be a direct descendant of a document.Document and newChild is a DocumentFragment with more than one Element child, or that has a Text child.oldChild by newChild would lead to Document with more than one Element as child.oldChild by newChild would lead to the presence of an Element node before a DocumentType node.NotFoundError DOMException
Thrown if the parent of oldChild is not the current node.
// Given:
// <div>
// <span id="childSpan">foo bar</span>
// </div>
// Create an empty element node
// without an ID, any attributes, or any content
const sp1 = document.createElement("span");
// Give it an id attribute called 'newSpan'
sp1.id = "newSpan";
// Create some content for the new element.
const sp1_content = document.createTextNode("new replacement span element.");
// Apply that content to the new element
sp1.appendChild(sp1_content);
// Build a reference to the existing node to be replaced
const sp2 = document.getElementById("childSpan");
const parentDiv = sp2.parentNode;
// Replace existing node sp2 with the new span element sp1
parentDiv.replaceChild(sp1, sp2);
// Result:
// <div>
// <span id="newSpan">new replacement span element.</span>
// </div>
| Specification |
|---|
| DOM> # dom-node-replacechild> |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
replaceChild |
1 | 12 | 1 | 7 | 1.1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 | 1 |
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild