Understanding the HTML DOM all Collection

The HTML DOM all collection is a legacy feature that provides access to all elements within an HTML document. While it’s not recommended for modern web development due to its quirks and performance implications, understanding its behavior can be useful, especially when dealing with older codebases.

The all collection is available as a property of the document object. It returns an HTMLCollection, which is a live collection of all elements in the document in the order they appear in the source code. This contrasts with querySelectorAll, which returns a static NodeList.

Purpose of the all Collection

The all collection was initially designed to provide a simple, straightforward way to access every single HTML element within a document. However, because of its live nature and some quirky behaviors, it is generally avoided in favor of more modern methods. It can be used for:

  • Quick Inspection: Rapidly accessing a list of all elements for debugging purposes.
  • Legacy Code Handling: Interacting with older JavaScript code that may rely on it.
  • Educational Understanding: Learning about the evolution of DOM APIs and why modern alternatives are preferred.

Syntax and Usage

The all collection is accessed as a property of the document object. Here’s how:

const allElements = document.all;

This returns an HTMLCollection which behaves like an array.

Key Characteristics

  • Live Collection: Changes to the DOM are immediately reflected in the all collection. This means elements added or removed after you retrieve the collection will be part of or excluded from the collection dynamically.
  • Order: Elements are listed in the order they appear in the source HTML.
  • Indexed Access: Elements can be accessed via numeric indices, similar to arrays, starting from 0.
  • Named Access (Legacy Feature): Elements can also be accessed via their id or name attribute using dot or bracket notation. This functionality is not consistent across all browsers and is not recommended for modern usage.

Practical Examples

Let’s look at how to use the all collection with some practical examples.

Basic Iteration

This example demonstrates how to iterate over all the elements in a document using a for...of loop.

<!DOCTYPE html>
<html>
<head>
    <title>DOM all Collection Example</title>
</head>
<body>
    <p>First paragraph.</p>

    <div>A div element</div>
    <span>A span element</span>
    <p>Second paragraph.</p>

<script>


        const allElements_example1 = document.all;
        for (const element of allElements_example1) {
            console.log(element.tagName);
        }


</script>

</body>
</html>

Output: (Check the console in your browser’s developer tools)

"HTML"
"HEAD"
"TITLE"
"BODY"
"P"
"DIV"
"SPAN"
"P"
"SCRIPT"

This code retrieves all elements using document.all and then logs the tag name of each element to the console.

Accessing Elements by Index

Here is how you can access elements by their index using the all collection.

<!DOCTYPE html>
<html>
<head>
    <title>DOM all Collection Example</title>
</head>
<body>
    <p>First paragraph.</p>

    <div>A div element</div>
    <span>A span element</span>
    <p>Second paragraph.</p>

<script>


        const allElements_example2 = document.all;
        console.log(allElements_example2[0].tagName); // HTML
        console.log(allElements_example2[2].tagName); // TITLE
        console.log(allElements_example2[4].tagName); // P (first <p> tag)


</script>

</body>
</html>

Output: (Check the console in your browser’s developer tools)

"HTML"
"TITLE"
"P"

This code shows how you can retrieve the tag names of specific elements based on their index within the all collection.

Live Collection Behavior

This example shows how the all collection updates live when elements are added to the DOM.

<!DOCTYPE html>
<html>
<head>
    <title>DOM all Collection Example</title>
</head>
<body>

    <div id="container">
        <p>First paragraph.</p>
    </div>

<script>


        const container_example3 = document.getElementById("container");
        const allElements_example3 = document.all;
        console.log("Before adding element, number of elements:", allElements_example3.length);

        // Add a new paragraph
        const newParagraph = document.createElement('p');
        newParagraph.textContent = "A new paragraph added";
        container_example3.appendChild(newParagraph);

       console.log("After adding element, number of elements:", allElements_example3.length);


</script>

</body>
</html>

Output: (Check the console in your browser’s developer tools)

"Before adding element, number of elements:" 5
"After adding element, number of elements:" 6

This example demonstrates that the all collection is live. Adding a new paragraph to the DOM increases the number of elements in the allElements_example3 collection.

Named Access (Not Recommended)

Here is an example of how to use names to access elements. This method is not recommended due to inconsistent browser behavior.

<!DOCTYPE html>
<html>
<head>
    <title>DOM all Collection Example</title>
</head>
<body>
    <p id="myParagraph">First paragraph.</p>

    <div name="myDiv">A div element</div>

<script>


        const allElements_example4 = document.all;
        console.log(allElements_example4.myParagraph.tagName);
        console.log(allElements_example4.myDiv.tagName);


</script>

</body>
</html>

Output: (Check the console in your browser’s developer tools)

"P"
"DIV"

This example shows how to access elements by their id and name attributes. Note that this named access can behave inconsistently across browsers and is generally discouraged.

Alternatives to document.all

The document.all collection is considered outdated, and modern JavaScript offers better alternatives:

  • document.querySelectorAll(): Returns a static NodeList of elements matching a CSS selector. This is the recommended way to select multiple elements.
  • document.getElementById(): Returns a single element with the specified ID.
  • document.getElementsByTagName(): Returns a live HTMLCollection of elements with the specified tag name.
  • document.getElementsByClassName(): Returns a live HTMLCollection of elements with the specified class name.

When to Avoid document.all

Avoid document.all in most cases because:

  • Performance: It can be less performant than more specific selectors like querySelectorAll.
  • Browser Compatibility: Although mostly supported, some older and specific browser versions may behave unpredictably.
  • Maintenance: It makes the code less readable and harder to maintain compared to more modern and specific selectors.
  • Named Access Inconsistency: Accessing elements by name is inconsistent and should be avoided.
  • Not Standard: document.all is a non-standard feature and may not be supported by all future browsers.

Browser Support

The document.all collection has decent support in most browsers, including:

Browser Support
Chrome Yes
Edge Yes
Firefox Yes
Safari Yes
Opera Yes

Note: While document.all is widely supported, it is always recommended to use modern alternatives for maintainable and efficient code. 💡

Conclusion

The HTML DOM all collection is a legacy feature that provides access to all elements in a document. While it can be useful for debugging and handling legacy code, its quirky behavior, performance implications, and non-standard nature make modern selectors like querySelectorAll and getElementById much better choices for contemporary web development. Understanding the all collection provides valuable historical context and underscores why specific and efficient selection methods are now standard practice. Always aim to use best practices to ensure performance, maintainability, and reliability of your code. ✅