HTML | DOM replaceChild() Method

The replaceChild() method in HTML DOM is used to replace a child node with a new node within the given parent node.

Syntax:

parentNode.replaceChild( newChild, oldChild )

Parameter Values: This method accept two parameters which are listed below:



  • newChild: It is the required parameter. It represents the new node which need to be inserted.
  • oldChild: It is the required parameter. It represents the node which is replaced by new node.

Return Value: It returns a node object which represents the replaced node.

Example: In this example the first <li> text is replaced with the new text.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>DOM replaceChild() Method</title>
    </head>
      
    <body>
      
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
          
        <h2>
            DOM replaceChild() Method
        </h2>
          
        <p>Sorting Algorithm</p>
        <ul id = "listitem"><li>Insertion sort</li>
            <li>Merge sort</li>
            <li>Bubble sort</li>
        </ul>
          
        <button onclick ="Geeks()">
            Click Here!
        </button>
      
        <script>
        function Geeks() {
            var doc = document.createTextNode("Quick sort");
            var list = document.getElementById("listitem").childNodes[0];
            list.replaceChild(doc, list.childNodes[0]);
        }
        </script>
      
    </body>
</html>                    

chevron_right


Output:
Before click on the button:
replaceChild
After click on the button:
replaceChild

Supported Browsers: The browser supported by DOM replaceChild() method method are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.