Imagine a structure like this:
<div id="boxes">
<div id="firstdiv">...</div>
<div class="important">...</div>
<div id="lastdiv">
<div id="subdiv">...</div>
<div class="important">...</div>
</div>
</div>
Now if I write:
document.querySelectorAll('#boxes > div:not([class])')
I will get #firstdiv
and #lastdiv
. Great.
But what if I want to do the same from the #boxes
element?
const boxes = document.querySelector('#boxes')
// this is what I tried
boxes.querySelectorAll('> div:not([class])') // it doesn't work
// and if I type
boxes.querySelectorAll('div:not([class])')
// I get #firstdiv, #lastdiv BUT ALSO #subdiv which I don't want
How can I do that?
You can use :scope
to reference the element the querySelectorAll
is being called on:
const collection = boxes.querySelectorAll(':scope > div:not([class])');
console.log(collection.length, collection[0], collection[1]);
<div id="boxes">
<div id="firstdiv">...</div>
<div class="important">...</div>
<div id="lastdiv">
<div id="subdiv">...</div>
<div class="important">...</div>
</div>
</div>
(unfortunately, it doesn't have great browser support, though)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With