When using querySelectorAll, is there a way to reference the immediate children of a node context without using identifiers?

Say I have an HTML structure like

<div id="a">
  <div id="b">
    <div id="c"></div>
  </div>
</div>

To execute a query for children of "a" using querySelectorAll, I can do something like

//Get "b", but not "c"
document.querySelectorAll('#a > div')

My question is : is it possible to do this without an identifier, directly referring to node? I tried to do

var a_div = document.getElementById('a')
a_div.querySelectorAll('> div') //<-- error here

but I get an error indicating that the selected selector is invalid.


And in case someone wonders, my real use case would be something more complicated like "> .foo.bar.baz", so I would rather avoid manually bypassing the DOM. I am currently adding a temporary id to the root div, but this seems like an ugly hack ...

+5
3

, () - . > , , () ( ).

BoltClock , API- Selectors API findAll name ", , , , (, , )".
, :

a_div.findAll('> div');
+4
document.querySelector('#a').querySelectorAll(':scope > div')

, , .

+8

I think I should misunderstand your question, but that is how I interpret it.

  
var a = document.getElementById('a')
var results = a.querySelectorAll('div');

results will contain all child divs.

-2
source

All Articles