使用`querySelectorAll`在DOM集合上使用子选择器 [英] Child selector using `querySelectorAll` on a DOM collection

查看:190
本文介绍了使用`querySelectorAll`在DOM集合上使用子选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设您有一个包含嵌套子列表的列表。

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?

推荐答案

编写一个rooted到当前元素的选择器的正确方法是使用 :scope

The correct way to write a selector that is "rooted" to the current element is to use :scope.

ul.querySelectorAll(":scope > li");

有关解释和强大的跨浏览器解决方案,请参阅我的答案:http://stackoverflow.com/a/21126966/1170723

See my answer here for an explanation and a robust, cross-browser solution: http://stackoverflow.com/a/21126966/1170723

这篇关于使用`querySelectorAll`在DOM集合上使用子选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆