removeChild

In this chapter you will learn:

  1. How to remove a node from another node
  2. How to remove the last node from its parent

Remove a child

The removeChild() method removes a node. This method accepts a single argument, which is the node to remove. The removed node is returned:

The following code removes first child from its parent.

<!DOCTYPE html><!--from   j av a  2 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 formerFirstChild = div.removeChild(div.firstChild); 
               document.writeln(formerFirstChild);

        </script>
    </body>
</html>

Click to view the demo

Remove the last node

The following code removes the last child.

<!DOCTYPE html><!--from   j a va 2s.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 formerLastChild = div.removeChild(div.lastChild); 
               document.writeln(formerLastChild);

        </script>
    </body>
</html>

Click to view the demo

A node removed via removeChild() 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 replace a node
  2. How to replace the last child
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