replaceChild()

replaceChild() method accepts two arguments:

  • the node to insert
  • the node to replace

The node to replace is returned

replace first child

 
<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <div id="div1">
            <ul>
                <li>List item 1</li>
                <li>List item 2</li>
                <li>List item 3</li>
            </ul>
        </div>
        <p id="p1">Hello <b>World!</b></p>
        
        
        <script type="text/javascript">
               var div = document.getElementById("div1");
               var p = document.getElementById("p1");
               
               var returnedNode = div.replaceChild(p, div.firstChild); 
               document.writeln(returnedNode);

        </script>
    </body>
</html>
  
Click to view the demo

Replace last child

 
<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <div id="div1">
            <ul>
                <li>List item 1</li>
                <li>List item 2</li>
                <li>List item 3</li>
            </ul>
        </div>
        <p id="p1">Hello <b>World!</b></p>
        
        
        <script type="text/javascript">
               var div = document.getElementById("div1");
               var p = document.getElementById("p1");
               
               var returnedNode = div.replaceChild(p, div.lastChild); 
               document.writeln(returnedNode);

        </script>
    </body>
</html>
  
Click to view the demo

A node removed via replaceChild() is still owned by the document but doesn't have a specific location in the document.

Home 
  JavaScript Book 
    DOM  

DOM Model:
  1. Document Object Model
  2. nodeName and nodeValue Properties
  3. Node Relationships:childNodes
  4. parentNode
  5. previousSibling and nextSibling properties
  6. lastChild and firstChild
  7. appendChild() adds a node to the end of the childNodes list
  8. insertBefore()
  9. ownerDocument property
  10. removeChild
  11. replaceChild()
  12. Working with Text
  13. Check the length of NodeList
  14. Convert NodeList to an Array
  15. html tag and its cooresponding JavaScript class