在DOM集合上使用`querySelectorAll`的子选择器 [英] Child selector using `querySelectorAll` on a DOM collection
问题描述
我们假设你有一个带有嵌套子列表的列表。
Let's presume you got a list with nested child lists.
<ul>
<li></li>
<li>
<ul>
<li></li>
<li></li>
</ul>
</li>
<li></li>
</ul>
并使用 document.querySelectorAll()
进行选择:
var ul = document.querySelectorAll("ul");
如何使用 ul
获得直接的子元素?
How can i use the ul
collection to get the direct child elements?
ul.querySelectorAll("> li");
// Gives 'Error: An invalid or illegal string was specified'
code> ul 以某种方式进行缓存(否则我可以直接完成 ul> li
。
Let's presume ul
is cached somehow (otherwise i could have done ul > li
directly).
在jQuery中这样做:
In jQuery this works:
$("ul").find("> li");
但它不在本机 querySelectorAll
。任何解决方案?
But it doesn't in native querySelectorAll
. Any solutions?
推荐答案
正确的方式来编写一个根植于当前元素的选择器是使用 :scope
。
The correct way to write a selector that is "rooted" to the current element is to use :scope
.
ul.querySelectorAll(":scope > li");
请参阅我的答案,了解一个解释和强大的跨浏览器解决方案: https://stackoverflow.com/a/21126966/1170723
See my answer here for an explanation and a robust, cross-browser solution: https://stackoverflow.com/a/21126966/1170723
这篇关于在DOM集合上使用`querySelectorAll`的子选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!