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 Create a Reusable Fetch Function

Crystal Vesely
Crystal Vesely
14,502 Points

Calling querySelector on a variable

I was under the assumption that querySelector was for the document object. But in this video, Guil calls querySelector on the variable card, which holds a reference to the “card” element on the DOM.

const card = document.querySelector(card);

Later on in the code, Guil calls

card.querySelector(img);

Could someone explain in more detail what is happening here. Thanks so much. I did try to research this on my own, but I couldn’t find any info.

Crystal Vesely
Crystal Vesely
14,502 Points

Sorry, he actually calls it on the class = ‘card’, not an element node. (I am still learning the terminology).

2 Answers

Steven Parker
Steven Parker
240,995 Points

All the document search functions can be applied to individual elements, in which case they will search for a match among that element's descendants. Of course, when applied to the document itself, all elements are descendants and therefore match candidates.

This makes it easy to search in a sub-tree of the document, which it what is being done in the lesson example. Note that the variable "card" is initialized as a reference to the element that has the class card:

const card = document.querySelector('.card');  // you forgot the period, which means class

So the 2nd example searches for the first "img" element that is a descendant of card.

Crystal Vesely
Crystal Vesely
14,502 Points

Thanks Steven!! That explains it so well!!!!