HTML DOM HTMLCollection Object: Accessing Collections of Elements

In the realm of web development, the Document Object Model (DOM) serves as a crucial bridge between your HTML structure and JavaScript code. The HTMLCollection object is a fundamental part of the DOM, providing a way to access and manipulate groups of HTML elements. Unlike NodeList, which can contain any type of node, HTMLCollection specifically consists of HTML elements. This guide delves into the intricacies of the HTMLCollection object, showing you how to effectively use it to manage your web page’s elements.

What is an HTMLCollection?

An HTMLCollection is an array-like object that contains a list of HTML elements. It is live, meaning that if the underlying document changes, the HTMLCollection is automatically updated. This dynamic behavior distinguishes it from static lists like arrays and NodeList objects.

HTMLCollection objects are primarily returned by methods like:

  • document.getElementsByClassName()
  • document.getElementsByTagName()
  • element.children

These methods return a collection of elements that match the specified criteria.

Key Characteristics of HTMLCollection

  • Live Updates: Reflects changes in the DOM dynamically. 🔄
  • Array-Like: Provides access to elements using numeric indices and the length property, but it’s not a true array and lacks array methods like forEach.
  • HTML Elements Only: Contains only HTML elements, not text nodes or comments.
  • Ordered: Elements appear in the order they appear in the HTML source.

Syntax

The HTMLCollection object does not have a constructor. You obtain it as a return value from various DOM methods. The key properties and methods include:

Property/Method Description
`length` Returns the number of elements in the collection.
`item(index)` Returns the element at the specified index. Returns `null` if the index is out of range.
`namedItem(name)` Returns an element with the specified `id` or `name`. Returns `null` if no such element exists.

Examples of Using HTMLCollection

Let’s explore several examples that demonstrate how to access and manipulate HTMLCollection objects.

Accessing Elements by Tag Name

The document.getElementsByTagName() method returns an HTMLCollection of all elements with a given tag name.

<!DOCTYPE html>
<html>
<head>
  <title>HTMLCollection Example</title>
</head>
<body>
  <h2>List of Items</h2>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>

<script>


    const listItems = document.getElementsByTagName("li");
    console.log("Number of list items:", listItems.length);

    for (let i = 0; i < listItems.length; i++) {
      console.log(listItems[i].textContent);
    }


</script>

</body>
</html>

Output:

Number of list items: 3
Item 1
Item 2
Item 3

This example shows how to retrieve all <li> elements using getElementsByTagName and then iterate over the collection to log their content.

Accessing Elements by Class Name

The document.getElementsByClassName() method returns an HTMLCollection of all elements with a given class name.

<!DOCTYPE html>
<html>
<head>
  <title>HTMLCollection Example</title>
</head>
<body>
  <h2>Shopping List</h2>
  <ul id="shopping-list-container">
    <li class="item">Milk</li>
    <li class="item special">Eggs</li>
    <li class="item">Bread</li>
  </ul>

<script>


    const items = document.getElementsByClassName("item");
    console.log("Number of items:", items.length);

    for (let i = 0; i < items.length; i++) {
      items[i].style.color = "blue";
    }

     const specialItems = document.getElementsByClassName("special");
     for (let i = 0; i < specialItems.length; i++) {
      specialItems[i].style.fontWeight = "bold";
    }


</script>

</body>
</html>

Output:

The list items ‘Milk’, ‘Eggs’ and ‘Bread’ will be colored in blue and the text ‘Eggs’ will also be in bold.

This example demonstrates how to style all elements with the class “item” and make the elements with class “special” bold using an HTMLCollection.

Using the item() Method

The item() method is used to retrieve a specific element by its index within the collection.

<!DOCTYPE html>
<html>
<head>
  <title>HTMLCollection Example</title>
</head>
<body>

  <div id="container-item">
    <p>First Paragraph</p>
    <p>Second Paragraph</p>
    <p>Third Paragraph</p>
  </div>

<script>


    const container = document.getElementById("container-item");
    const paragraphs = container.children;

    const firstParagraph = paragraphs.item(0);
    const secondParagraph = paragraphs.item(1);

     if(firstParagraph){
      firstParagraph.style.backgroundColor = "lightgreen";
    }

    if(secondParagraph){
       secondParagraph.style.backgroundColor = "lightblue";
    }

    console.log("First paragraph:", firstParagraph.textContent);
    console.log("Second paragraph:", secondParagraph.textContent);


</script>

</body>
</html>

Output:

The background color of the first paragraph will be set to lightgreen and the second paragraph to lightblue. The output to console will be:

First paragraph: First Paragraph
Second paragraph: Second Paragraph

This example shows how to retrieve specific elements from an HTMLCollection using the item() method by index.

Using the namedItem() Method

The namedItem() method retrieves an element by its id or name attribute. It is useful when you need to access a specific element directly by name, rather than by its numerical index, if the elements are nested inside a parent element.

<!DOCTYPE html>
<html>
<head>
  <title>HTMLCollection Example</title>
</head>
<body>
  <form id="my-form">
    <input type="text" id="username" name="user" value="John Doe">
    <input type="email" id="email" name="email" value="[email protected]">
  </form>

<script>


    const formElement = document.getElementById("my-form");
    const formElements = formElement.elements;

    const usernameInput = formElements.namedItem("username");
    const emailInput = formElements.namedItem("email");
    const userNamedInput = formElements.namedItem("user");


     if(usernameInput){
      usernameInput.style.border = "2px solid green";
    }

     if(emailInput){
      emailInput.style.border = "2px solid blue";
    }


    console.log("Username input value:", usernameInput.value);
     console.log("User input value using name:", userNamedInput.value);
    console.log("Email input value:", emailInput.value);


</script>

</body>
</html>

Output:

The border of the username input field will be green and the email input will have a blue border. The output in console will be:

Username input value: John Doe
User input value using name: John Doe
Email input value: [email protected]

This example demonstrates how to use the namedItem() method to directly access form elements by their id and name attributes.

Example of live collection

HTMLCollection is a live collection. This example demonstrate this property:

<!DOCTYPE html>
<html>
<head>
  <title>HTMLCollection Example</title>
</head>
<body>
  <ul id="live-list-container">
    <li id="item1">Item 1</li>
    <li id="item2">Item 2</li>
  </ul>

  <button id="add-list-item">Add list item</button>

<script>


    const listContainer = document.getElementById("live-list-container");
    const listItems = listContainer.children;

    console.log("Initial number of items:", listItems.length);

    document.getElementById("add-list-item").addEventListener("click", () => {
      const newListItem = document.createElement("li");
      newListItem.textContent = `Item ${listItems.length + 1}`;
      listContainer.appendChild(newListItem);
      console.log("After adding the new item, number of list items:", listItems.length); // This will be updated automatically
     });


</script>

</body>
</html>

Output:

The initial number of list items will be 2. Every time the button “Add list item” is clicked, new list item will be added and the log output will be updated showing the new length of the list.

This example shows how changes to the DOM are immediately reflected in the HTMLCollection.

HTMLCollection vs NodeList

While both HTMLCollection and NodeList represent collections of nodes in the DOM, there are key differences:

  • Type of Nodes: HTMLCollection contains only HTML elements, while NodeList can contain any node type (elements, text nodes, comments).
  • Live vs. Static: HTMLCollection is always live, whereas NodeList can be either live (e.g., returned by element.childNodes) or static (e.g., returned by document.querySelectorAll()).
  • Methods: HTMLCollection does not have array methods like forEach(), unlike some NodeList objects.
Feature HTMLCollection NodeList
Node Types Only HTML Elements All Node Types (Elements, Text, Comments)
Live Collection Always live Can be live or static
Array Methods Limited Some have `forEach`, others not

Understanding these differences is crucial when working with the DOM and choosing the appropriate collection type.

Conclusion

The HTMLCollection object is a vital tool for web developers, providing dynamic access to collections of HTML elements in the DOM. By using methods like getElementsByTagName(), getElementsByClassName(), item(), and namedItem(), you can efficiently manipulate and manage your web page’s elements. Understanding the dynamic nature of HTMLCollection and its distinction from NodeList is crucial for building responsive and maintainable web applications. 🚀