Here's a quiz for you: Given the HTML below, what element will be returned by the querySelector()
call? Note that the .wrapper
is outside the .main
element.
<div class="wrapper">
<div class="main">
<div class="content"></div>
</div>
</div>
const main = document.querySelector(".main");
const content = main.querySelector(".wrapper .content");
// What's the result???
Don't cheat! Think about it for a second.
If you call querySelector()
or querySelectorAll()
on an element, you will only get elements within that element. However, the query itself will be applied to the whole document. So the above code will return the <div class="content"></div>
node.
You can include the :scope
pseudo-class to apply the query to the element itself:
const main = document.querySelector(".main");
const content = main.querySelector(":scope .wrapper .content");
// Result: null
This is also useful to query direct children of an element:
const main = document.querySelector(".main");
const content = main.querySelector(":scope > .child");
// --> Does not include nested .child elements