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
Lee Cockcroft
5,147 PointsquerySelector and querySelectorAll
Hi All,
Could you please explain something to me.
I understand querySelector will selects the first element, and ALL will select them all.
What I don't get is, why do we need to loop the querySelectorAll? As surely when you create a const, you're selecting all of that particular Elements?
So eg..
count list = document.querySelectorALL("li") ;
Surely that's selecting all the li's? so...
list.style.color="blue";
Technically should change their color blue, but it doesn't unless I loop it??
Thanks
3 Answers
Angelica Hart Lindh
19,465 PointsHi Lee,
I understand your theory, and in principle it was something that got me too.
However, it is important to understand what the querySelectorAll() method returns. According to the Javascript MDN:
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
So we know that the querySelectorAll method returns a nodeList and we can find out about a nodeList from this:
NodeList objects are collections of nodes such as those returned by Node.childNodes and the document.querySelectorAll method. Although NodeList is not an Array, it is possible to iterate on it using forEach(). Several older browsers have not implemented this method yet.
My advice going forward would be to make use of the resources available to you, such as the Mozilla Developer Network, as they can really help understand things with some good examples and explanations.
Here's my jsFiddle
Cheers
Steven Parker
243,266 Points
You can only change a property on one element at a time.
A collection of elements has no "style" property, but each individual element does. That's why you use a loop to access them.
Instead of elements, imagine you had some dials with color settings — you could easily set one dial to a particular color setting. But if you had a box full of them (a collection), you couldn't just set a color on the box itself. You'd have to go through the box and set each dial individually.
Lee Cockcroft
5,147 PointsThank you for your help