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) Traversing the DOM Using parentNode to Traverse Up the DOM

David Castro
David Castro
2,340 Points

How did he use listdiv.querySelector? list div isnt even the class on the element, the class is "list

Th entire time we were taught to use document.querySelector its weird that he used it this way with no explanation.

1 Answer

Steven Parker
Steven Parker
231,261 Points

You didn't show the code, so I'm guessing you are talking about this line:

const listUl = listDiv.querySelector("ul");

And here, "listDiv" is an element that was previously identified in the code, and this line uses it as the starting point in the DOM to find the first "ul" element inside it.

SAMUEL LAWRENCE
SAMUEL LAWRENCE
Courses Plus Student 8,447 Points

Hi Steven Parker can you expound a bit on this. I too have this question and I don't quite understand your explanation. He's been using the document to target elements all the time and he didn't explain or mention before that you could target elements in the DOM in that way. While I sort of understand what is going on here, in that the document.querySelector('.list'); was already used to target the div with the class of .list in the DOM I had no idea you could then use, items that were already targeted in that way, and what's the rule or syntax for doing it correctly? Dave McFarland and when I changed the code to

const listUL = document.querySelector('ul');

it also worked. But it would be nice if he explained a bit more on how to do things in that way. I'm guessing it could reduce the amount lines of code we write.

Steven Parker
Steven Parker
231,261 Points

These are the same as long as the ul in the listDiv is also the first one on the whole document. Otherwise, you would need a more specific selector. So to safely change the starting point of the query:

const listUL = listDiv.querySelector("ul");         // the equivalent of this...
const listUL = document.querySelector('.list ul');  // ...would be this