Dev.to AI 🤖 Ai 👁 0 📖 1 min read

"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 JavaScri

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>

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);
<!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>
📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.