Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make querySelectorAll select only from child elements of the current element

What I'm asking is how to implement the equivalent functionality of jQuery's children() with HTML5's querySelector/querySelectorAll, i.e. how do I designate the current element in the selector pattern.

For example:

  <div id="foo">
    <div class="bar" id="div1">
      <div class="bar" id="div1.1">
      </div>
    </div>
    <div class="bar" id="div2"></div>
  </div>

With document.getElementById('foo').querySelectAll('div.bar') all three divs will be selected. What if I only wanna get div1 and div2, not div1's child div1.1? How do I write [[current node]] > div.bar like css selector?

Could anybody shed some light on this?

like image 900
Need4Steed Avatar asked Feb 14 '23 20:02

Need4Steed


2 Answers

In your example you have did id="foo", so above example works.

But in a situation when parent element has no ID, but you still want to use querySelectorAll to get immediate children - it is also possible to use :scope to reference element like this:

    var div1 = document.getElementById('div1'); //get child
    var pdiv = div1.parentNode; //get parent wrapper
    var list = pdiv.querySelectorAll(':scope > div.bar');

Here query will be "rooted" to pdiv element..

like image 127
megamurmulis Avatar answered Feb 17 '23 11:02

megamurmulis


Actually there is a pseudo-class :scope to select the current element, however, it is not designated as being supported by any version of MS Internet Explorer.

document.getElementById('foo').querySelectAll(':scope>div.bar')
like image 41
Quasimodo's clone Avatar answered Feb 17 '23 10:02

Quasimodo's clone