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

document.querySelector() vs. element.querySelector

Take this html

<body>
  <h1>Main Title</h1>
  <section>
    <h1>Section Title</h1>
  </section>
</body>

If I were to use element.querySelector as:

section.querySelector("h1")

it would return the first h1 from the section element. If I was to use

document.querySelector("h1")

it would return the first h1 starting from the root.

Is this correct?

2 Answers

Steven Parker
Steven Parker
243,318 Points

It looks like you've got it!

Your description is precisely correct, assuming that a variable named section had already been created and assigned as a reference to the <section> element.

var section = document.querySelector("section");

Yes. That is correct.

For a demonstration take a look at this JSFiddle that I made based on your examples. If you open the console on that page you'll see the "Section Title" is printed first and then the "Main Title" second.