Categories
JavaScript Answers

How to Correctly Iterate Through Elements Returned by getElementsByClassName?

Spread the love

One way to iterate through elements returned by the document.getElementsByClassName method is to use the for-of loop.

For instance, if we have the following HTML:

<div class='slide'>
  foo
</div>
<div class='slide'>
  bar
</div>
<div class='slide'>
  baz
</div>

Then we can get all the elements with the class slide and loop through each item by writing:

const slides = document.getElementsByClassName("slide");
for (const slide of slides) {
  console.log(slide);
}

We call document.getElementsByClassName with 'slide' to return an HTML element collection object with all the divs.

Then we use the for-of loop to loop through each item.

slide has the div we’re looping through.

We can also spread the slides object into an array and then call forEach on it:

const slides = document.getElementsByClassName("slide");
[...slides].forEach(slide => {
  console.log(slide);
})

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *