JavaScript: Nodes versus Collections

Understanding HTML Collections and Node Lists in JavaScript



When working with the DOM in JavaScript, you often encounter two types of collections: HTML Collections and Node Lists. Both represent groups of DOM elements, but they have distinct characteristics and behaviors. This guide will explain the differences between them, demonstrate how to iterate over each using different `for` loops, and provide tips on choosing the correct loop for your needs.

HTML Collections

HTML Collection is a live collection of DOM elements. This means that if the document changes (e.g., an element is added or removed), the HTML Collection updates automatically.

Common Methods Returning HTML Collections:

  • document.getElementsByTagName(tagName)
  • document.getElementsByClassName(className)
  • document.forms
  • document.images

Example:

<!DOCTYPE html>

<html>

<body>

    <div class="example">Item 1</div>

    <div class="example">Item 2</div>

    <div class="example">Item 3</div>

    <script>

        const items = document.getElementsByClassName('example');

        // Using a classic for loop

        for (let i = 0; i < items.length; i++) {

            console.log(items[i].innerText);

        }

        // Adding a new element

        const newDiv = document.createElement('div');

        newDiv.className = 'example';

        newDiv.innerText = 'Item 4';

        document.body.appendChild(newDiv);

        // The collection is live and updates automatically

        console.log('After adding new element:');

        for (let i = 0; i < items.length; i++) {

            console.log(items[i].innerText);

        }

    </script>

</body>

</html>

Key Points:

  • HTML Collections are live; they reflect changes in the document automatically.
  • Use `for` loops for iteration, as HTML Collections do not have array methods like `forEach`.

Node Lists

Node List can be either live or static. A live Node List updates automatically when the document changes, while a static Node List does not.

Common Methods Returning Node Lists:

  • document.querySelectorAll(selector)` (static)
  • document.childNodes` (live)

Example:

<!DOCTYPE html>

<html>

<body>

    <div class="example">Item 1</div>

    <div class="example">Item 2</div>

    <div class="example">Item 3</div>

    <script>

        const items = document.querySelectorAll('.example'); // Static Node List

        // Using a for...of loop

        for (const item of items) {

            console.log(item.innerText);

        }

        // Adding a new element

        const newDiv = document.createElement('div');

        newDiv.className = 'example';

        newDiv.innerText = 'Item 4';

        document.body.appendChild(newDiv);

        // The static Node List does not update automatically

        console.log('After adding new element:');

        for (const item of items) {

            console.log(item.innerText);

        }

        // Retrieving the Node List again

        const updatedItems = document.querySelectorAll('.example');

        console.log('After retrieving Node List again:');

        for (const item of updatedItems) {

            console.log(item.innerText);

        }

    </script>

</body>

</html>

Key Points:

  • Node Lists can be live or static depending on how they are obtained.
  • Static Node Lists do not reflect changes in the document after their creation
  • Node Lists can use `for...of` loops and array methods like `forEach` if converted to an array using `Array.from`.

Choosing the Correct Loop

HTML Collections:

  • Use a classic `for` loop (`for (let i = 0; i < items.length; i++)`) because HTML Collections do not have array methods
    • Example: Iterating over elements with `getElementsByClassName` or `getElementsByTagName`.

Node Lists:

  • Use a `for...of` loop or array methods (`items.forEach(...)`) for ease and readability.
    • Example: Iterating over elements with `querySelectorAll`.

Interacting with the DOM:

  • Live Collections (HTML Collections and live Node Lists):** Automatically update when the document changes. Useful when you need real-time updates.
  • Static Node Lists:** Do not update automatically. Useful for performance when you do not need real-time updates.

Summary

Understanding the differences between HTML Collections and Node Lists, and knowing how to iterate over them effectively, is crucial for efficient DOM manipulation. Here are the takeaways:

  • HTML Collections:** Live, use classic `for` loops.
  • Node Lists:** Can be live or static, use `for...of` loops or convert to arrays for more methods.
  • Choosing the Right Loop:** Depends on the type of collection and whether you need real-time updates or not.

By mastering these nuances, you can write more efficient and robust JavaScript code that interacts seamlessly with the DOM.

Comments

Popular posts from this blog

Why Certifications Methods?

CCNP 03 - WANS

LPI E - ALL K.D.