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 trialkaran Badhwar
Web Development Techdegree Graduate 18,135 PointsIterating 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
231,269 PointsAn 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.
karan Badhwar
Web Development Techdegree Graduate 18,135 PointsThankyou Steven, I really appreciate it