To replace a child node with new node javascript has provided a method called "replaceChild()". To achieve this task at first we have to create a new node and then by using replaceChild(), we should replace the old node with new node.
syntax
node.replaceChild(newnode, oldnode);
It takes two parameters i.e old and new nodes and replaces the old node with a new node.
Example
In the following example, initially, the unordered list consists of elements Boost, Horlicks, and Maltova. After replacing the first element with Bournavita using replaceChild(), the output we get is Bournavita, Horlicks, and Maltova as shown in the output
<html> <body> <ul id="List"><li>Boost</li><li>Horlicks</li><li>Maltova</li></ul> <script> var newnode = document.createTextNode("Bournavita"); var item = document.getElementById("List").childNodes[0]; item.replaceChild(newnode, item.childNodes[0]); </script> </body> </html>
Output
Bournavita Horlicks Maltova