appendChild

In this chapter you will learn:

  1. How to add a child to an element

Add a child

appendChild() adds a node to the end of the childNodes list. appendChild() returns the newly added node.

<!DOCTYPE html><!--from jav a  2s .com-->
<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.appendChild(p); 
               document.writeln(returnedNode == p); //true 
               document.writeln(div.lastChild == p); //true 


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

Click to view the demo

If the node passed into appendChild() is already part of the document, it is removed from its previous location and placed at the new location.

Next chapter...

What you will learn in the next chapter:

  1. Insert before another element
  2. How to insert as the new first child
  3. How to insert before 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