JavaScript

coding learning websites codepractice

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


What Are DOM Collections?

In JavaScript, a DOM Collection is a group of DOM elements returned by certain methods or properties. Unlike a single element, DOM collections allow you to access, loop through, and manipulate multiple elements at once.

DOM Collections are live or static, depending on how they are retrieved. Understanding collections is essential for efficiently modifying multiple elements dynamically.

Types of DOM Collections

  1. HTMLCollection – A live collection of HTML elements. Changes in the DOM are automatically reflected in the collection.

    • Examples: document.forms, document.images, element.children.

  2. NodeList – A collection of nodes that can include elements, text nodes, and comments. NodeLists can be live or static, depending on the method used.

    • Examples: document.querySelectorAll() returns a static NodeList.

    • element.childNodes returns a live NodeList.

Accessing DOM Collections

HTMLCollection

// Access all forms on the page
let forms = document.forms;
console.log(forms); // HTMLCollection of all form elements

// Access a form by index
console.log(forms[0]); // First form on the page

// Access all child elements of a container
let container = document.querySelector(".container");
console.log(container.children); // HTMLCollection of element children
  • HTMLCollections do not include text nodes or comments.

  • They are live, so any changes in the DOM are reflected immediately.

NodeList

// Select all paragraphs
let paragraphs = document.querySelectorAll("p");
console.log(paragraphs); // NodeList (static)

// Access first paragraph
console.log(paragraphs[0]);

// Child nodes (live NodeList including text)
let childNodes = document.querySelector(".container").childNodes;
console.log(childNodes);
  • NodeLists can include text nodes depending on the method.

  • Static NodeLists do not update automatically, while live NodeLists (like childNodes) reflect changes.

Looping Through Collections

Using for loop

let items = document.querySelectorAll("li"); // NodeList

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

Using for…of loop (ES6)

for (let item of items) {
    item.style.backgroundColor = "lightgray"; // Add background
}

Using forEach (for NodeList only)

items.forEach((item, index) => {
    item.textContent = `Item ${index + 1}`; // Update text content
});

HTMLCollections do not support forEach directly. You can convert them to an array using Array.from().

let children = document.querySelector(".container").children;
Array.from(children).forEach(child => {
    child.style.border = "1px solid black";
});

Common DOM Collections

  1. document.forms – All <form> elements.

  2. document.images – All <img> elements.

  3. document.links – All <a> elements with an href attribute.

  4. document.scripts – All <script> elements.

  5. element.children – Child elements of a given element.

  6. element.childNodes – All child nodes, including text nodes and comments.

Live vs Static Collections

  • Live Collection: Updates automatically when the DOM changes.

    let liveChildren = document.querySelector(".container").children;
    let newDiv = document.createElement("div");
    document.querySelector(".container").appendChild(newDiv);
    console.log(liveChildren.length); // Includes newDiv
    
  • Static Collection: Does not update automatically.

    let staticList = document.querySelectorAll("div"); // Static NodeList
    let newDiv2 = document.createElement("div");
    document.body.appendChild(newDiv2);
    console.log(staticList.length); // Does NOT include newDiv2
    

Knowing whether a collection is live or static is crucial to avoid bugs in dynamic applications.

Practical Example: Manipulating Multiple Elements

<ul class="menu">
    <li>Home</li>
    <li>About</li>
    <li>Services</li>
    <li>Contact</li>
</ul>
let menuItems = document.querySelectorAll(".menu li"); // NodeList (static)

menuItems.forEach((item, index) => {
    item.style.padding = "10px";
    item.style.cursor = "pointer";

    // Highlight every even item
    if (index % 2 === 0) {
        item.style.backgroundColor = "#f0f0f0";
    }
});
  • Loops through all items and applies styling dynamically.

  • Static NodeList is suitable here because items are not added/removed dynamically.

Converting Collections

Sometimes, you need an array to use advanced array methods:

let children = document.querySelector(".container").children; // HTMLCollection
let childrenArray = Array.from(children); // Convert to array

childrenArray.map(child => {
    child.style.fontWeight = "bold";
});
  • Conversion allows use of map, filter, reduce, etc.

Best Practices

  • Use querySelectorAll for static NodeLists when the DOM structure is stable.

  • Use children or childNodes when accessing all child elements or nodes.

  • Convert HTMLCollections to arrays when you need array methods.

  • Prefer NodeLists for batch operations on multiple elements.

  • Be aware of live vs static collections to prevent unexpected behavior.

Summary of the Tutorial

DOM Collections are groups of elements or nodes that allow batch access and manipulation. Key points:

  • HTMLCollection – Live, elements only, returned by forms, images, children.

  • NodeList – Can be static or live, includes elements and optionally text nodes.

  • Loop through collections using for, for…of, forEach, or convert to array for advanced methods.

  • Understanding live vs static collections is crucial for dynamic DOM updates.

  • DOM Collections simplify bulk operations, making web applications more interactive and efficient.

Mastering DOM Collections allows you to work with multiple elements at once, making your JavaScript code more efficient, cleaner, and scalable.


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.


JavaScript

online coding class codepractice

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