Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.