DEV Community

Cover image for How to Loop Through an HTMLCollection

How to Loop Through an HTMLCollection

isabelxklee profile image isabel k. lee Updated on ・2 min read

If you've ever written a frontend application in JavaScript, you've probably run into HTMLCollections.

I recently deployed Plant Flashcards, a full-stack application where you can learn about plant facts and test your knowledge. I used a vanilla JavaScript for the frontend and a homegrown Rails API for the backend! Interacting with JSON objects and trying to manipulate elements on the DOM made me realize that HTMLCollections were very different from plain ole, regular Arrays.

HTMLCollections are array-like objects that return HTML elements on the DOM. Unlike regular Arrays, they’re “live” objects, so they’ll change automatically depending on the contents of the DOM.

Let's dive in

Here's an example of a variable that will return an HTMLCollection. In this line of code, we're pulling all the elements from the document object that have the class name plant. We're then assigning it to a variable called plantsArray.

let plantsArray = document.getElementsByClassName("plant")

And here's what plantsArray might look like when logged to the console:

Example of an HTMLCollection

The difference between HTMLCollections and Arrays

Out of all the CRUD (Create, Read, Update, Delete) operations, HTMLCollections are mainly used for reading elements. They’re not meant for DOM manipulation because they're live objects. Arrays, on the other hand, can be easily mutated.

HTMLCollections also have different built-in properties and methods than Arrays.

See what happens when we try to access the individual elements in an HTMLCollection like we would with an Array.

plantsArray.forEach((plant) => {

=> TypeError: plantsArray.forEach is not a function

Trying to run a .forEach() method on plantsArray gives us a TypeError. HTMLCollections may look like Arrays and are also technically a list of objects, but they are fundamentally different.

How to loop through an HTMLCollection

1) If we want to be able to use the .forEach() method, we can turn the HTMLCollection into an Array, then call the method on it.

Array.from(plantsArray).forEach((plant) => {

=> "Monstera", "ZZ Plant", "Snake Plant"

2) Run a for/of loop.

for (plant of plantsArray) {

=> "Monstera", "ZZ Plant", "Snake Plant"

3) Run a for loop.

for (i = 0; i < plantsArray.length; i++) {

=> "Monstera", "ZZ Plant", "Snake Plant"


Get comfortable interacting with HTMLCollections and their unique properties and methods!


Geeks for Geeks
Stack Overflow discussion
Pawel Grzybek's blog
Hacker Noon

Discussion (0)

Editor guide