DEV Community

Cover image for "Understanding createElement() and appendChild() in JavaScript DOM"
Karthick (k)
Karthick (k)

Posted on

"Understanding createElement() and appendChild() in JavaScript DOM"

What is the DOM?

WITH THE DOM API in JavaScript, you can manipulate the HTML document effectively. The DOM (Document Object Model, Dom ApI provide set of functions and methods to modify the HTML dynamically in JavaScript

createElement() :

In JavaScript, document.createElement() is a built-in DOM method used to dynamically create a new HTML element in the browser's memory.

Simple Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const h1=document.createElement("h1")

        console.log(h1)


        const p=document.createElement("p");
        p.textContent="Hello"

        console.log(p);
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

What is appendChild() Method

The appendChild() is a method of the Node interface. The appendChild() method allows you to add a node to the end of the list of child nodes of a specified parent node.

Syntax:

parentNode.appendChild(childNode);
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>appendChild</title>
</head>
<body>
    <ul id="Menu"></ul>

    <script>
        const li=document.createElement("li");

        li.textContent='Home'

        const Men=document.querySelector("#Menu")
        Men.appendChild(li);
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)