Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

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

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...