HTML - DOM appendChild() Method



The HTML DOM appendChild() method is used to add a new child node (element) as the last child node into the specified parent node.

This method returns the appended child node. If the node already exists in the document, it is first removed from its current parent before being appended to the new parent.

You can only append one child node at a time. To append multiple nodes, you need to call this method multiple times.

Syntax

Following is the syntax of the HTML DOM appendChild() method −

element.appendChild(newNode);

Parameters

This method accepts a single parameter as listed below −

Parameter Description
newNode It represents the new child node that will be added to the parent element.

Return Value

This method returns the appended child node that has been added to the parent element. If an error occurs during the append operation, it returns 'null'.

Example 1: Nested Appends to Documents

The example below helps you to understand how nested appends work by adding a paragraph inside a

and then appending the div to the document −




HTML DOM appendChild()



Before

Appended with new paragraph content

New paragraph added to the inner div.

Example 2: Adding Paragraphs Dynamically

Following is another example of HTML DOM appendChild() method, which shows how you can add paragraphs dynamically to a web page −




HTML DOM appendChild()


Adding Paragraph dynamically

click on button to see the added paragraph content...

Example 3: Creating a Simple List

This example shows how you can create a simple list dynamically(runtime). When the "Add List" button is clicked, a new list (i.e., li element) gets added to the Unordered list (ul)




HTML DOM appendChild()


Creates a List

click on the button to append more list items....

    Example 4: Inserting Images Dynamically

    In the following example, we are using the appendChild() method to append an image dynamically into a web page −

    
    
    
    HTML DOM appendChild()
    
    
    

    Inserts an Image Dynamically

    Clicking the button appends more images...

    Example 5: Adding Text Nodes

    This example shows how to add a text node to an existing HTML element using the HTML DOM appendChild() method −

    
    
    
    HTML DOM appendChild()
    
    
    

    Appending Text Nodes

    Before Appending Text Node:

    After Appending Text Node:

    This is some initial content.

    Supported Browsers

    Method Chrome Edge Firefox Safari Opera
    appendChild() Yes Yes Yes Yes Yes
    html_dom_element_reference.htm
    Advertisements