Javascript Reference - HTML DOM appendChild() Method








The appendChild() method adds a node as the last child of a node.

Browser Support

appendChild Yes Yes Yes Yes Yes

Syntax

node.appendChild(node)

Parameters

Parameter Type Description
node Node object Required. The node object to append




Return Value

The appended node as Node type object.

Example

The following code shows how to move a list item from one list to another.


<!DOCTYPE html>
<html>
<body>
<ul id="myList1"><li>A</li><li>B</li></ul>
<ul id="myList2"><li>C</li><li>D</li></ul>
<button onclick="myFunction()">test</button>
<script>
function myFunction()<!--  w w w . j a va 2  s. c  om-->
{
    var node=document.getElementById("myList2").lastChild;
    document.getElementById("myList1").appendChild(node);
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to add an item in a list.


<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>A</li><li>B</li></ul>
<button onclick="myFunction()">test</button>
<script>
function myFunction(){<!--   w  w  w  . j a v  a  2s .c  o m-->
    var node=document.createElement("LI");
    var textnode=document.createTextNode("Water");
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code adds a click event listener to a button. When you click the button it adds table row to SurveysBody table.

<!DOCTYPE HTML> 
<html> 
    <body> 
        <table border="1"> 
            <tbody> 
                <tr><td>A</td><td>B</td></tr> 
                <tr id="apple"><td>C</td><td>D</td></tr> 
            </tbody> 
        </table> 
        <br/>
        <table border="1"> 
            <tbody id="SurveysBody"> 
                <tr><td>E</td><td>F</td></tr> 
            </tbody> 
        </table> 
        <p> 
            <button id="move">Move Row</button> 
        </p> 
        <script> 
            document.getElementById("move").onclick = function() { 
                var elem = document.getElementById("apple"); 
                document.getElementById("SurveysBody").appendChild(elem); 
            }; <!--  w w w  .j  a va2 s  .c o m-->
        </script> 
    </body> 
</html>

Click to view the demo