JavaScript’s Node.replaceChild()
method replaces a child node within the Node
.
Syntax
Node.replaceChild(newChild, oldChild);
Parameters
newChild
The Node
object to replace oldChild
.
If newChild
is a reference to an existing node in the document, the method moves the node from its current position to the new position.
oldChild
The Node
object to be replaced.
Return value
The replaced node (oldChild
).
Exceptions
HierarchyRequestError
DOMException
Thrown when the constraints of the DOM are violated (for example, when the node that replaces another node is an ancestor of the parent node, which leads to a cycle).
NotFoundError DOMException
Thrown if the parent of oldChild
is not the current node.
Examples
Here are some examples of using the JavaScript replaceChild()
method.
Suppose we have the following lists of programming languages:
<ul id="list">
<li>JavaScript</li>
<li>Python</li>
</ul>
<ul id="newList">
<li>C#</li>
</ul>
We would like to replace C# with JavaScript. How could we do that?
One way to do that is to select the second list with the getElementById()
method, select the first li
elements of both lists, and use the replaceWith()
method:
let newList = document.getElementById('newList');
let newChild = document.querySelector('#list li:first-child');
let oldChild = document.querySelector('#newList li:first-child');
newList.replaceChild(newChild, oldChild);
Now our HTML looks like this:
<ul id="list">
<li>Python</li>
</ul>
<ul id="newList">
<li>JavaScript</li>
</ul>
If we only had the second list, we could replace C# with JavaScript by creating a new li
element:
let newList = document.getElementById('newList');
let newChild = document.createElement('li');
newChild.textContent = 'JavaScript';
let oldChild = document.querySelector('#newList li:first-child');
newList.replaceChild(newChild, oldChild);
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
replaceChild() |
1 | 12 | 1 | 6 | 7 | 1.1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |