Javascript 在 DOM 集合上使用 `querySelectorAll` 的子选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10189903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Child selector using `querySelectorAll` on a DOM collection
提问by Husky
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>
And use document.querySelectorAll()
to make a selection:
并用于document.querySelectorAll()
进行选择:
var ul = document.querySelectorAll("ul");
How can i use the ul
collection to get the direct child elements?
我如何使用ul
集合来获取直接子元素?
ul.querySelectorAll("> li");
// Gives 'Error: An invalid or illegal string was specified'
Let's presume ul
is cached somehow (otherwise i could have done ul > li
directly).
让我们假设ul
以某种方式缓存(否则我可以ul > li
直接完成)。
In jQuery this works:
在 jQuery 中,这有效:
$("ul").find("> li");
But it doesn't in native querySelectorAll
. Any solutions?
但它不在 native 中querySelectorAll
。任何解决方案?
回答by lazd
The correct way to write a selector that is "rooted" to the current element is to use :scope
.
编写“根植”到当前元素的选择器的正确方法是使用:scope
.
ul.querySelectorAll(":scope > li");
See my answer here for an explanation and a robust, cross-browser solution: https://stackoverflow.com/a/21126966/1170723
有关解释和强大的跨浏览器解决方案,请参阅我的答案:https: //stackoverflow.com/a/21126966/1170723
回答by alex
Because the ul
returned is a NodeList, it doesn't implicitly loop over its contents like a jQuery collection. You'd need to use ul[0].querySelectorAll()
or better still select the ul
with querySelector()
.
因为ul
返回的是一个 NodeList,它不会像 jQuery 集合那样隐式地循环它的内容。您需要使用ul[0].querySelectorAll()
或更好地选择ul
with querySelector()
。
Besides that, querySelectorAll()
won't take a >
and work from its current context. However, you can get it to work using lazd's answer(though check the browser compatibility), or any of these workarounds (which should have no browser issues)...
除此之外,querySelectorAll()
不会>
从当前上下文中获取和工作。但是,您可以使用lazd 的答案(尽管检查浏览器兼容性)或任何这些解决方法(应该没有浏览器问题)让它工作...
[].filter.call(ul.querySelectorAll("li"), function(element){
return element.parentNode == ul;
});
This will select all li
elements that are descendants of your ul
, and then remove the ones which are not direct descendants.
这将选择li
作为您的后代的所有元素,ul
然后删除不是直接后代的元素。
Alternatively, you could get all childNodes
and then filter them...
或者,您可以获取所有内容childNodes
然后过滤它们...
[].filter.call(ul.childNodes, function(node) {
return node.nodeType == 1 && node.tagName.toLowerCase() == 'li';
});
回答by Alnitak
You need to iterate over the NodeList
returned by document.querySelectorAll()
and then call element.querySelectorAll()
for each element in that list.
您需要遍历NodeList
返回的 by document.querySelectorAll()
,然后调用element.querySelectorAll()
该列表中的每个元素。