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

John Lukacs
John Lukacs
26,806 Points

Targeting Javascript in Javascript and the Dom Section 5 video 1

The const listUL = listDiv.querySelector("ul"); should not the thing read? Was this a mistake? wasen't it

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

4 Answers

Ioannis Leontiadis
Ioannis Leontiadis
9,828 Points

Hello John,

there is document.querySelector() and element.querySelector(). In this case both return the same value.

All in all, as document.querySelector() uses a depth-first pre-order traversal of the document's nodes it would be more efficient to use element.querySelector() when you know that what you are looking for is a child of an element.

Hi John here is why we are using listDiv.querySelector instead of document.querySelector("ul")

Remember how Guil said in one of his video it is better to target the parent element that is as close to the the target as possible?

Here is why we do that. If we use document.querySelector("ul") that will work fine for this project. However let's imagine you add some more code in a few days time to your project and that code has another set of UL & LI before the one you already have. Now everytime you run your event listener your event listener function will run on all your UL. To eliminate that problem we are using listDiv.

We are basically telling the browser that give us the UL only within the listDiv. Don't perform our action on any other list dive. This is called the rule of specificity. In web development the more specific you are the better in most cases.

Hope that helps.

John Lukacs
John Lukacs
26,806 Points

So it was a mistake? Or can element of the element.querySelector be anything

Ioannis Leontiadis
Ioannis Leontiadis
9,828 Points

It was not a mistake. Because the <ul> is inside the <div id='listDiv'>, listDiv.querySelector('ul') is equivalent and faster than document.querySelector('ul').

John Lukacs
John Lukacs
26,806 Points

Ok I see it. Im a newb sorry

Ioannis Leontiadis
Ioannis Leontiadis
9,828 Points

No worries, keep up and do not forget to pay a visit at mdn for such things : )