JavaScript JavaScript and the DOM 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
173,991 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
Pro 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
173,991 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