top of page

Learn through our Blogs, Get Expert Help, Mentorship & Freelance Support!

Welcome to Colabcodes, where innovation drives technology forward. Explore the latest trends, practical programming tutorials, and in-depth insights across software development, AI, ML, NLP and more. Connect with our experienced freelancers and mentors for personalised guidance and support tailored to your needs.

blog cover_edited.jpg

HTML Collections in JavaScript

Writer's picture: samuel blacksamuel black

When working with the DOM (Document Object Model) in JavaScript, you often need to access and manipulate multiple elements at once. One of the ways JavaScript provides access to groups of elements is through HTMLCollections.

In this tutorial, we will explore what an HTMLCollection is, how it works, and how it differs from other similar objects like NodeList.

HTML Collections in JavaScript - colabcodes

What is an HTMLCollection?

An HTMLCollection is an array-like object that represents a live collection of elements in the DOM. Unlike static lists, an HTMLCollection updates dynamically as elements are added or removed from the document. This makes HTMLCollections useful for real-time manipulation of elements but also requires careful handling to avoid unintended side effects in loops and iterations.


How to Access an HTMLCollection

There are several ways to obtain an HTMLCollection in JavaScript, depending on the type of elements you need to select. These methods return a live collection, meaning any changes to the DOM automatically reflect in the collection.


Using document.getElementsByTagName()

Retrieves a live HTMLCollection of elements matching the specified tag name.

let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs); // Outputs an HTMLCollection of all <p> elements

Using document.getElementsByClassName()

Retrieves an HTMLCollection of elements matching a specified class name.

let items = document.getElementsByClassName("item");
console.log(items); // Outputs an HTMLCollection of elements with class 'item'

Using document.forms, document.images, and document.links

These built-in document properties return live HTMLCollections:


  • document.forms: All <form> elements.

  • document.images: All <img> elements.

  • document.links: All <a> elements with an href attribute.


console.log(document.forms); 
console.log(document.images); 
console.log(document.links);

HTMLCollection vs NodeList

A NodeList is a collection of nodes, which can be elements, text nodes, or other DOM nodes. It is returned by various DOM methods such as document.querySelectorAll() and childNodes. Although HTMLCollection and NodeList may seem similar, they have key differences:

Feature

HTMLCollection

NodeList

Live Collection

Yes, updates dynamically

Static unless returned by childNodes

Index Access

Yes

Yes

forEach Method

No

Yes (for static NodeList)

Access Methods

getElementsByTagName, getElementsByClassName

querySelectorAll, childNodes

Looping Through an HTMLCollection

Since an HTMLCollection is array-like but not a true array, it does not support forEach(). Here are ways to iterate through it:


Using a Traditional for Loop:

let elements = document.getElementsByClassName("item"); 
for (let i = 0; i < elements.length; i++) {     
	console.log(elements[i].innerText); 
}

Using the for...of Loop:

let items = document.getElementsByClassName("item"); 
for (let item of items) {     
	console.log(item.innerText); 
}

Converting to an Array and Using forEach:

let elementsArray = Array.from(document.getElementsByClassName("item")); elementsArray.forEach(element => console.log(element.innerText));

HTMLCollection is Live

An HTMLCollection is a collection of DOM (Document Object Model) nodes, typically representing elements within a webpage, such as all the <div>, <p>, or <a> tags in the document. One of the key features of HTMLCollection is that it is "live," meaning that it automatically updates to reflect changes in the DOM. For example, if elements are added or removed from the page dynamically, the HTMLCollection will instantly reflect these changes without requiring a manual refresh or re-querying. This is different from an Array, which is static and would require explicit updating if the underlying DOM changes. While live collections are useful for real-time interaction with the DOM, they can sometimes be less predictable or performant compared to static collections, especially when working with complex or rapidly changing pages.

let divs = document.getElementsByTagName("div");
console.log(divs.length); // Assume 3 divs exist

document.body.appendChild(document.createElement("div"));
console.log(divs.length); // Now, length is 4 because HTMLCollection updates dynamically

Conclusion

HTMLCollection is a powerful way to access multiple elements in the DOM efficiently. However, because it is not a true array, it requires different handling compared to a NodeList.


Key Takeaways:

  • HTMLCollection is an array-like object, not an actual array.

  • It is live, meaning it updates dynamically when the DOM changes.

  • It can be accessed via getElementsByTagName, getElementsByClassName, and document properties like forms, images, and links.

  • It does not have array methods like forEach(), but can be converted into an array using Array.from().



By mastering HTMLCollections, you will enhance your JavaScript DOM manipulation skills, making your code more efficient and powerful.

Comments


Get in touch for customized mentorship and freelance solutions tailored to your needs.

bottom of page