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 (Retiring) Getting a Handle on the DOM Select All Elements of a Particular Type

Elise St Hilaire
Elise St Hilaire
13,358 Points

Why do we have to use a for loop, instead of applying the style color to myList directly?

I tried to get the color of the list items to change color by using this code:

myList.style.color = 'purple';

...but it looks like you can't select a whole group like that. Why do we have to use the for loop instead?

5 Answers

Steven Parker
Steven Parker
229,695 Points

:point_right: An element collection does not have a style property.

But a single element does, and that's why you would use a loop to set the property on each element individually.

You might enjoy learning about jQuery, one of the most popular libraries for JavaScript. It represents elements and collections with special objects, so the methods work the same with one item or more without looping.

Mars Epaecap
Mars Epaecap
5,110 Points

Good question thanks for asking :)

Had the same issue, thanks for asking and thanks for the answer:)

Janet Leon
Janet Leon
6,908 Points

I did this to to change the unordered list directly instead of looping:

let myList = document.getElementsByTagName("ul"); myList[0].style.color = "purple";

Though I can see the benefit of learning how to loop through in these instances.

Harold Thompson
Harold Thompson
18,157 Points

Awesome, thanks for asking. Steven for the save again.

Thanks Steven