When using querySelectorAll, is there a way to ref

2019-01-27 23:40发布

Say I have an HTML structure like

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

To do a query for the 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 the ID, referencing the node directly? I tried doing

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

but I get an error telling me that the selector I used is invalid.


And in case anyone is wondering, my real use case would be something more complicated like '> .foo .bar .baz' so I would prefer to avoid manual DOM traversal. Currently I am adding a temporary id to the root div but that seems like an ugly hack...

3条回答
劳资没心,怎么记你
2楼-- · 2019-01-27 23:58
document.querySelector('#a').querySelectorAll(':scope > div')

I am not sure about browser support, but I use it on chrome and chrome mobile packaged apps and it works fine.

查看更多
forever°为你锁心
3楼-- · 2019-01-28 00:03

No, there isn't a way (yet) to reference all childs of some element without using a reference to that element. Because > is a child combinator, which represents a relationship between a parent and child element, a simple selector (a parent) is necessary (which is missing in you example).

In a comment, BoltClock said that the Selectors API Level 2 specification defines a method findAllname may change "which accepts as an argument what will probably be known as a relative selector (a selector that can start with a combinator rather than a compound selector)".
When this is implemented, it can be used as follows:

a_div.findAll('> div');
查看更多
放荡不羁爱自由
4楼-- · 2019-01-28 00:20

I think I must be misunderstanding your question, but this is how I'm interpreting it..

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

results will hold all your child divs now.

查看更多
登录 后发表回答