Node: replaceChild() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
ThereplaceChild() method of theNode interface replaces a child node within the given (parent) node.
In this article
Syntax
replaceChild(newChild, oldChild)Parameters
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 beforeold, is unusual.Element.replaceWith(), applying only to nodes that are elements,may be easier to read and use.
Return value
The replacedNode. This is the same node asoldChild.
Exceptions
HierarchyRequestErrorDOMExceptionThrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs:
- If the parent of
oldChildis not aDocument,DocumentFragment, or anElement. - If the replacement of
oldChildbynewChildwould lead to a cycle, that is ifnewChildis an ancestor of the node. - If
newChildis not aDocumentFragment, aDocumentType, anElement, or aCharacterData. - If the current node is a
Text, and its parent is aDocument. - If the current node is a
DocumentTypeand its parent isnot aDocument, as adoctype should always be a direct descendant of adocument. - If the parent of the node is a
DocumentandnewChildis aDocumentFragmentwith more than oneElementchild, or that has aTextchild. - If the replacement of
oldChildbynewChildwould lead toDocumentwith more than oneElementas child. - If the replacement of
oldChildbynewChildwould lead to the presence of anElementnode before aDocumentTypenode.
- If the parent of
NotFoundErrorDOMExceptionThrown if the parent of
oldChildis not the current node.
Example
// Given:// <div>// <span>foo bar</span>// </div>// Create an empty element node// without an ID, any attributes, or any contentconst sp1 = document.createElement("span");// Give it an id attribute called 'newSpan'sp1.id = "newSpan";// Create some content for the new element.const sp1Content = document.createTextNode("new replacement span element.");// Apply that content to the new elementsp1.appendChild(sp1Content);// Build a reference to the existing node to be replacedconst sp2 = document.getElementById("childSpan");const parentDiv = sp2.parentNode;// Replace existing node sp2 with the new span element sp1parentDiv.replaceChild(sp1, sp2);// Result:// <div>// <span>new replacement span element.</span>// </div>Specifications
| Specification |
|---|
| DOM> # dom-node-replacechild> |