Using querySelector
or querySelectorAll
in JavaScript, you can easily find descendants of a node that match a given selector.
But what if you want to find only children (i.e. direct descendants) of an element?
Easy: use :scope
. It references the element on which DOM API methods are being called:
element.querySelectorAll(':scope > .your-selector')
Example
Consider this HTML
<body>
<div id="container1">
<div id="container1a">foo</div>
<div id="container1b">bar</div>
<div id="container1c">baz</div>
</div>
<div id="container2">
Hello Universe
</div>
</body>
without :scope
A simple document.body.querySelectorAll('div')
will return a NodeList with 5 items, i.e. all 5 divs from above.
with :scope
Using document.body.querySelectorAll(':scope > div')
you'll receive a NodeList with the 2 children of body:
- The
container1
element - The
container2
element
Browser Support
:scope
is
supported in all browsers
Show archive.org snapshot
for the JavaScript DOM API.
Posted by Arne Hartherz to makandra dev (2023-08-04 13:07)