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

Why use a for loop instead of selecting the entire tag list?

Why do we have to iterate through the list of Li tags using a for loop to make them purple? Why can't we directly assign the color purple to myList itself?

For example:

myList.style.color = 'purple';

Why doesn't the above code work?

1 Answer

Jamie Reardon
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jamie Reardon
Treehouse Project Reviewer

Because it is an HTMLCollection that is an array-like element. In plain English, it doesn't work because you are trying to style the array.

That is why you use a for loop to iterate through the array to style the individual li elements. Without the loop, you would be tediously repeating code.

To learn more properties and methods of an object to see which ones you can apply to the current element you are trying to manipulate, you can open up Devtools JavaScript Console and enter the name of the variable myList and use the up and down arrow keys to cycle through the available properties and methods that are usable on it.