JavaScript JavaScript and the DOM Getting a Handle on the DOM Select All Elements of a Particular Type

Karan Sheth
Karan Sheth
2,431 Points

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
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.