JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM Collections


JavaScript DOM Collections are lists of HTML elements returned by the DOM when you select multiple elements at once. These collections allow you to work with groups of elements instead of handling each element separately. Understanding DOM collections is very important because most real websites deal with multiple buttons, links, inputs, cards, rows, and sections at the same time.

In this tutorial, you will learn what DOM collections are, different types of DOM collections, how to access them, how to loop through them, common mistakes, best practices, and real-world examples.

What Are DOM Collections

A DOM Collection is an array-like object that contains multiple DOM elements. It looks similar to an array but it is not exactly the same.

DOM collections are usually returned by methods like:

  • getElementsByTagName()

  • getElementsByClassName()

  • getElementsByName()

  • document.forms

  • document.images

  • document.links

These collections update automatically when the DOM changes in some cases, which makes them powerful but sometimes tricky.

Why DOM Collections Are Important

DOM collections are important because:

  • Websites often contain repeated elements

  • You need to apply the same logic to multiple elements

  • It reduces duplicate code

  • It improves maintainability

  • It makes dynamic UI updates easier

For example, validating all input fields, adding click events to buttons, or styling multiple cards is much easier with DOM collections.

Types of DOM Collections

There are mainly two types of collections you should understand.

HTMLCollection

An HTMLCollection is a live collection of elements. This means it updates automatically when elements are added or removed from the DOM.

Returned by:

  • getElementsByTagName()

  • getElementsByClassName()

  • document.forms

  • document.images

  • document.links

NodeList

A NodeList can be live or static, depending on how it is created.

Returned by:

  • querySelectorAll() (static)

  • childNodes (live)

Understanding the difference between HTMLCollection and NodeList helps prevent bugs.

Using getElementsByTagName

This method selects elements by their tag name.

let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs);

This returns an HTMLCollection of all <p> elements.

Accessing elements:

paragraphs[0].style.color = "blue";

Looping through:

for (let i = 0; i < paragraphs.length; i++) {
    paragraphs[i].style.fontSize = "16px";
}

Using getElementsByClassName

This method selects elements by class name.

let cards = document.getElementsByClassName("card");

Applying styles to all cards:

for (let i = 0; i < cards.length; i++) {
    cards[i].style.border = "1px solid #ddd";
}

This collection updates automatically if new elements with the same class are added.

Using getElementsByName

This method selects elements by the name attribute, commonly used in forms.

let inputs = document.getElementsByName("gender");

Checking values:

inputs.forEach(input => {
    if (input.checked) {
        console.log(input.value);
    }
});

Note that browser support for forEach may vary, so looping with for is safer.

Built-in DOM Collections

The DOM provides some built-in collections that are frequently used.

document.forms

Returns all forms on the page.

let forms = document.forms;
console.log(forms.length);

Accessing a form:

let loginForm = document.forms[0];

document.images

Returns all images.

let images = document.images;
for (let i = 0; i < images.length; i++) {
    images[i].style.borderRadius = "8px";
}

document.links

Returns all anchor tags with an href.

let links = document.links;
console.log(links.length);

HTMLCollection Characteristics

HTMLCollection has some important characteristics:

  • It is live

  • It has length property

  • Elements are accessed by index

  • It does not support array methods like map() or filter()

Example of live behavior:

let divs = document.getElementsByTagName("div");
console.log(divs.length);

let newDiv = document.createElement("div");
document.body.appendChild(newDiv);

console.log(divs.length);

The length updates automatically.

NodeList Characteristics

NodeList looks similar but behaves differently.

let buttons = document.querySelectorAll("button");

Important points:

  • Usually static

  • Supports forEach()

  • Length does not change automatically

buttons.forEach(button => {
    button.style.backgroundColor = "orange";
});

Converting DOM Collections to Arrays

To use array methods, convert the collection into an array.

let cardsArray = Array.from(cards);

cardsArray.map(card => {
    card.style.boxShadow = "0 4px 10px rgba(0,0,0,0.1)";
});

This is useful when you need advanced operations like filtering or mapping.

Looping Through DOM Collections

You can loop through collections using:

for Loop

for (let i = 0; i < cards.length; i++) {
    cards[i].style.padding = "15px";
}

for...of Loop

for (let card of cards) {
    card.style.marginBottom = "10px";
}

forEach (NodeList only)

buttons.forEach(btn => {
    btn.addEventListener("click", () => {
        alert("Button clicked");
    });
});

Practical Examples

Example 1: Add Event to All Buttons

let buttons = document.getElementsByTagName("button");

for (let button of buttons) {
    button.addEventListener("click", function() {
        this.classList.toggle("active");
    });
}

Example 2: Form Validation Using document.forms

let form = document.forms["signup"];

form.addEventListener("submit", function(event) {
    let username = form["username"].value;
    if (username === "") {
        alert("Username is required");
        event.preventDefault();
    }
});

Example 3: Highlight All Required Inputs

let inputs = document.getElementsByTagName("input");

for (let input of inputs) {
    if (input.required) {
        input.style.borderColor = "red";
    }
}

Example 4: Gallery Image Hover Effect

let images = document.images;

for (let img of images) {
    img.addEventListener("mouseover", function() {
        this.style.transform = "scale(1.05)";
    });

    img.addEventListener("mouseout", function() {
        this.style.transform = "scale(1)";
    });
}

Common Mistakes

  • Treating DOM collections like arrays

  • Forgetting that HTMLCollection is live

  • Modifying DOM while looping incorrectly

  • Using className instead of classList

  • Not converting collections when needed

Best Practices

  • Use querySelectorAll() when you need a static list

  • Use HTMLCollection when live updates are useful

  • Convert collections to arrays for complex logic

  • Keep loops efficient

  • Avoid unnecessary DOM queries

Real-World Use Cases

  • Adding event listeners to multiple elements

  • Bulk form validation

  • Dynamic menus and navigation

  • Applying themes to multiple components

  • Managing UI states in dashboards

Summary of JavaScript DOM Collections

JavaScript DOM Collections allow you to work efficiently with groups of elements. Whether it is an HTMLCollection or a NodeList, understanding how they behave helps you avoid bugs and write cleaner code. By learning how to loop through collections, convert them into arrays, and apply logic properly, you gain full control over large sections of your web page. DOM collections are a foundational concept for building scalable and interactive front-end applications.


Practice Questions

  1. Access all <p> elements on a page using querySelectorAll and change their text color.

  2. Use document.forms to log the names of all forms on a page.

  3. Loop through all child elements of a container using children and add a border to each.

  4. Convert an HTMLCollection returned by document.images into an array and log the src of each image.

  5. Use querySelectorAll to select all list items in a menu and highlight every odd item.

  6. Access all links on a page using document.links and add target="_blank" to each.

  7. Select all <div> elements using getElementsByTagName and change their background color.

  8. Access child nodes using childNodes and log the node type of each child.

  9. Add a new <li> element to a list and check if the children HTMLCollection updates automatically.

  10. Loop through a NodeList returned by querySelectorAll and append the text (Updated) to each element.


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top