You are here: Reference > JavaScript > client-side > HTML DOM > methods > appendChild

appendChild method

Browser support:
Inserts an element after the last child of the current element.
If the element has a parent element, then it will be removed from the parent element before the insertion. The inserted element will be the last element in the childNodes collection of the current element.
  • If you want to create a new element for insertion, use the createElement method first, then use the appendChild method for the newly created element.
  • To insert an element before a specified child of the current element, use the insertBefore method.
  • If you need to insert a new row into a table or a new cell into a row, you can also use the insertRow and insertCell methods.
  • Or, if you want to remove a child from an element, use the removeChild method.
Note: the appendChild method cannot be used for elements that belong to another document. Use the adoptNode or importNode method on foreign elements first.

Syntax:

object.appendChild (elementToAppend);
You can find the related objects in the Supported by objects section below.

Parameters:

elementToAppend
Required. Reference to the element to insert.

Return value:

Returns the newly inserted element.

Example HTML code 1:

This example illustrates the use of the appendChild method.
<head>
    <script type="text/javascript">
        function AddAChild () {
            var newElem = document.createElement ("div");
            newElem.innerHTML = "sample text";
            newElem.style.color = "red";

            var container = document.getElementById ("container");
            container.appendChild (newElem);
        }
    </script>
</head>
<body>
    <button onclick='AddAChild ();'>Add a div element to the container!</button>
    <div id="container"></div>
</body>
Did you find this example helpful? yes no

Example HTML code 2:

This example uses the innerHTML property to implement the same functionality as the previous example:
<head>
    <script type="text/javascript">
        function AddAChild () {
            var container = document.getElementById ("container");
            container.innerHTML += "<div style='color:red'>sample text</div>";
        }
    </script>
</head>
<body>
    <button onclick='AddAChild ();'>Add a div element to the container!</button>
    <div id="container"></div>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content