DOM Collections

DOM collections are arrays of DOM nodes, such as elements, that are returned by methods like getElementsByTagName or getElementsByClassName. These collections are live, meaning they automatically update when the DOM changes.

Key Topics

Accessing Collections

Use methods like getElementsByTagName or getElementsByClassName to access DOM collections.

const paragraphs = document.getElementsByTagName("p");
console.log("Number of paragraphs:", paragraphs.length);

Output

> Number of paragraphs: 3

Explanation: The getElementsByTagName method retrieves all <p> elements as a live collection, and its length is logged to the console.

Iterating Through Collections

Collections can be iterated using loops like for, for...of, or converted to arrays for advanced operations.

const items = document.getElementsByClassName("item");
for (let i = 0; i < items.length; i++) {
    console.log(`Item ${i + 1}:`, items[i].textContent);
}

Output

> Item 1: Item A

> Item 2: Item B

> Item 3: Item C

Explanation: The for loop iterates through the live collection, logging the text content of each item.

Modifying Collections

Since DOM collections are live, modifying the DOM directly updates the collection.

const list = document.getElementsByTagName("ul")[0];
const newItem = document.createElement("li");
newItem.textContent = "New Item";
list.appendChild(newItem);

console.log("Updated List Length:", list.getElementsByTagName("li").length);

Output

> Updated List Length: 4

Explanation: Adding a new <li> element updates the live collection, reflecting the new total number of items.

JavaScript Usage in DOM

Below is a complete DOM example demonstrating how to access, iterate through, and modify collections dynamically.

<!DOCTYPE html>
<html>
    <head>
        <title>DOM Collections Example</title>
    </head>
    <body>
        <ul>
            <li class="item">Item A</li>
            <li class="item">Item B</li>
            <li class="item">Item C</li>
        </ul>
        <script>
            const items = document.getElementsByClassName("item");
            console.log("Original List Length:", items.length);

            const newItem = document.createElement("li");
            newItem.textContent = "Item D";
            document.querySelector("ul").appendChild(newItem);

            console.log("Updated List Length:", items.length);
        </script>
    </body>
</html>

Key Takeaways

  • Access Collections: Use methods like getElementsByTagName or getElementsByClassName.
  • Iterate Collections: Use loops or convert to arrays for more operations.
  • Live Updates: DOM collections reflect changes to the DOM in real-time.
  • Dynamic Interaction: Manipulating collections allows for flexible and interactive web applications.