Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM Getting a Handle on the DOM Use CSS Queries to Select Page Elements

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Iterating over HTML Collection

As Guil, said we cannot Iterate Over HTMLCollection exactly Just like an array.

But we were able to Iterate over highlight Variable holding the reference to .highlight classes with (for...of) loop, How was that possible then?

const highlights = document.getElementsByClassName('.highlight');

for (const highlight of highlights){
  highlight.style.backgroundColor = 'cornsilk';
}

2 Answers

Steven Parker
Steven Parker
231,275 Points

An HTMLCollection doesn't have the same methods as an array, but it is still an iterable and can be used as the source for a loop variable.

So, while MyHTMLCollection.forEach(...); won't work, for (element of MyHTMLCollection) ... is OK.