replaceChild

In this chapter you will learn:

  1. How to replace a node
  2. How to replace the last child

Replace a child

replaceChild() method accepts two arguments:

  • the node to insert
  • the node to replace

The node to replace is returned

The following code replaces the first child from its parent.

<!DOCTYPE html><!--from  java2 s .  c o  m-->
<html>
    <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><!--   j a  v  a  2 s.co  m-->
<html>
    <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.

Next chapter...

What you will learn in the next chapter:

  1. How to work with DOM text
Home » Javascript Tutorial » DOM
Document Object Model
Node Type
nodeName and nodeValue
childNodes
parentNode
previousSibling and nextSibling
lastChild and firstChild
appendChild
insertBefore
ownerDocument
removeChild
replaceChild
Text
NodeList Length
DOM classes