How to Create, Update, and Delete DOM Elements πŸš€ | JavaScript Journey | In Hindi | Death Code - DeathCode

Managing DOM Elements in JavaScript

Example Code

Below is an example of creating, updating, and deleting elements in the DOM:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM Example</title>
</head>
<body>
    <h1 id="heading">JS Course By DeathCode</h1>
    <ul id="fruits">
        <li id="fruit">Mango</li>
        <li id="fruit">Orange</li>
        <li id="fruit">Grapes</li>
    </ul>
    <script src="index.js"></script>
</body>
</html>

Creating, Updating, and Deleting Elements

1. Creating New Elements

To create a new element, use the document.createElement method. You can then set attributes or content and append it to the DOM.

function addFruit(name) {
    const fruits = document.getElementById("fruits");
    const li = document.createElement('li');
    li.setAttribute("id", "fruit");
    li.textContent = name;
    fruits.appendChild(li);
}
 
addFruit("Strawberry");
addFruit("Blackberry");

2. Updating Elements

You can update the content or attributes of an existing element dynamically.

function changeFruitsColor(color) {
    const fruits = document.querySelectorAll("#fruit");
    fruits.forEach(ele => {
        ele.style.color = color;
    });
}
 
changeFruitsColor("yellow");

3. Deleting Elements

To remove an element, use the remove method or replace it with another element.

const lastFruit = document.querySelector("ul li:last-child");
lastFruit.remove();
 
const fruit = document.querySelector("ul li:nth-child(2)");
const li = document.createElement('li');
li.textContent = "Blackberry";
fruit.replaceWith(li);

NodeList vs HTMLCollection

NodeList and HTMLCollection are both collections of DOM elements, but they have key differences:

  • NodeList: A static or live list of nodes. Can be iterated using forEach (if static).
  • HTMLCollection: A live collection of elements that updates automatically when the DOM changes. Cannot be iterated directly with forEach.

Neither of these are true JavaScript arrays, so methods like map or filter are not directly available. You can convert them to arrays using Array.from or the spread operator.

// Converting NodeList to Array
const nodeList = document.querySelectorAll("li");
const nodeArray = Array.from(nodeList);
nodeArray.forEach(node => console.log(node.textContent));
 
// Converting HTMLCollection to Array
const htmlCollection = document.getElementsByTagName("li");
const htmlArray = [...htmlCollection];
htmlArray.forEach(node => console.log(node.textContent));
Β© 2024 DeathCode. All Rights Reserved.