Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to querySelector children (only) from an element?

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?

like image 374
vdegenne Avatar asked Dec 31 '22 16:12

vdegenne


1 Answers

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)

like image 70
CertainPerformance Avatar answered Jan 13 '23 15:01

CertainPerformance