Node.replaceChild()
The replaceChild()
method of the Node
element
replaces a child node within the given (parent) node.
Syntax
replaceChild(newChild, oldChild);
Parameters
newChild
-
The 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.
oldChild
-
The 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.
Return value
The replaced Node
. This is the same node as oldChild
.
Exceptions
HierarchyRequestError
DOMException
-
Thrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs:
- If the parent of
oldChild
is not aDocument
,DocumentFragment
, or anElement
. - If the replacement of
oldChild
bynewChild
would lead to a cycle, that is ifnewChild
is an ancestor of the node. - If
newChild
is not aDocumentFragment
, aDocumentType
, anElement
, or aCharacterData
. - If the current node is a
Text
, and its parent is aDocument
. - If the current node is a
DocumentType
and its parent is not aDocument
, as a doctype should always be a direct descendant of a document. - If the parent of the node is a
Document
andnewChild
is aDocumentFragment
with more than oneElement
child, or that has aText
child. - If the replacement of
oldChild
bynewChild
would lead toDocument
with more than oneElement
as child. - If the replacement of
oldChild
bynewChild
would lead to the presence of anElement
node before aDocumentType
node.
- If the parent of
NotFoundError
DOMException
-
Thrown if the parent of
oldChild
is not the current node.
Example
// 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>
Specifications
Specification |
---|
DOM Standard # dom-node-replacechild |
Browser compatibility
BCD tables only load in the browser