In this section, we will learn what the replaceChild() method is and how to use it in JavaScript.
What is Element replaceChild() Method in JavaScript?
The JavaScript Element replaceChild() method is used to replace a child of an element with a new one.
Note: after calling this method, the old child of the element will be gone from the DOM and so users won’t see it anymore.
JavaScript replaceChild() Method Syntax:
element.relaceChild(newNode, oldNode);
JavaScript replaceChild() Method Parameter
The method takes two arguments:
- The first argument is the new node that we want to use as the replacement of a child by the target element.
- The second argument is the old node (the child) that we want to replace it with a new node (the first argument).
JavaScript replaceChild() Method Return Value
The return value of this method is a reference to the old node (the child that is the second argument of the method) that was replaced with the new node.
Note: the value null will return if the operation failed.
Example: using replaceChild() method in JavaScript
See the Pen using replaceChild() method in JavaScript by Omid Dehghan (@odchan1) on CodePen.
Note that if you set the first argument of the replaceChild() method to an element that is already in the page, that element will be moved from its current position (including its entire children as well) and will be pasted as the replacement of the old element (the second argument of this method).