Skip to content

JavaScript appendChild() method

  • by

The appendChild() method in JavaScript is a built-in method that allows you to add a new child element to an existing parent element in the HTML DOM. This method appends the new child element to the end of the list of child elements for the parent element.

The syntax for the appendChild() method is as follows:

parentElement.appendChild(childElement);

Here, parentElement is the element to which you want to add a new child element, and childElement is the element that you want to add.

JavaScript appendChild() method example

Simple example code.

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript appendChild() Method Example</title>
</head>
<body>
    <div id="parent">
        <p>This is the parent element.</p>
    </div>

    <button onclick="addNewChild()">Add New Child</button>

    <script>
        function addNewChild() {
            // Create a new child element
            var newElement = document.createElement("p");
            newElement.textContent = "This is the new child element.";

            // Get the parent element
            var parentElement = document.getElementById("parent");

            // Append the new child element to the parent element
            parentElement.appendChild(newElement);
        }
    </script>
</body>
</html>

Output:

JavaScript appendChild() method

If you want to add the new child element to a specific position in the list of child elements, you can use the insertBefore() method instead.

Moving a node within the document

Use the appendChild() and removeChild() methods together to move the node from its current position to a new position.

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Move Node Example</title>
</head>
<body>
    <div id="parent">
        <p>This is the parent element.</p>
        <p id="child">This is the child element.</p>
    </div>

    <button onclick="moveNode()">Move Node</button>

    <script>
        function moveNode() {
            // Get the child element
            var childElement = document.getElementById("child");

            // Get the parent element
            var parentElement = document.getElementById("parent");

            // Remove the child element from its current position
            parentElement.removeChild(childElement);

            // Add the child element to the end of the parent element
            parentElement.appendChild(childElement);
        }
    </script>
</body>
</html>

The appendChild() can be used to move an existing child node to the new position within the document.

Comment if you have any doubts or suggestions on this HTML DOM Element appendChild() topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading