使用 querySelectorAll 检索直接子级 [英] Using querySelectorAll to retrieve direct children

查看:15
本文介绍了使用 querySelectorAll 检索直接子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以做到:

<div id="myDiv">
   <div class="foo"></div>
</div>

myDiv = getElementById("myDiv");
myDiv.querySelectorAll("#myDiv > .foo");

也就是说,我可以成功检索 myDiv 元素的所有具有类 .foo 的直接子元素.

That is, I can successfully retrieve all the direct children of the myDiv element that have class .foo.

问题是,我必须在选择器中包含 #myDiv 让我很困扰,因为我在 myDiv 元素上运行查询(显然多余的).

The problem is, it bothers me that I must include the #myDiv in the selector, because I am running the query on the myDiv element (so it is obviously redundant).

我应该可以关闭 #myDiv,但是选择器不是合法的语法,因为它以 > 开头.

I ought to be able to leave the #myDiv off, but then the selector is not legal syntax since it starts with a >.

有谁知道如何编写一个选择器,它只获取运行选择器的元素的直接子元素?

Does anyone know how to write a selector which gets just the direct children of the element that the selector is running on?

推荐答案

好问题.在被问到的时候,一种普遍实现的方式来执行组合器根查询".(正如 John Resig 称它们为)不存在.

Good question. At the time it was asked, a universally-implemented way to do "combinator rooted queries" (as John Resig called them) did not exist.

现在引入了 :scope 伪类.[pre-Chrominum] 上不支持Edge 或 IE 版本,但 Safari 已经支持几年了.使用它,您的代码可能会变成:

Now the :scope pseudo-class has been introduced. It is not supported on [pre-Chrominum] versions of Edge or IE, but has been supported by Safari for a few years already. Using that, your code could become:

let myDiv = getElementById("myDiv");
myDiv.querySelectorAll(":scope > .foo");

请注意,在某些情况下,您还可以跳过 .querySelectorAll 并使用其他好的老式 DOM API 功能.例如,您可以只写 myDiv.children,而不是 myDiv.querySelectorAll(":scope > *").

Note that in some cases you can also skip .querySelectorAll and use other good old-fashioned DOM API features. For example, instead of myDiv.querySelectorAll(":scope > *") you could just write myDiv.children, for example.

否则,如果您还不能依赖 :scope,我想不出另一种方法来处理您的情况而不添加更多自定义过滤器逻辑(例如 find myDiv.getElementsByClassName("foo").parentNode === myDiv),如果您尝试支持一个真正只想将任意选择器字符串作为输入和匹配列表作为输出!但如果像我一样,你最终问这个问题仅仅是因为你陷入了思考你所拥有的只是一把锤子"的想法.不要忘记 DOM 还提供了多种其他工具.

Otherwise if you can't yet rely on :scope, I can't think of another way to handle your situation without adding more custom filter logic (e.g. find myDiv.getElementsByClassName("foo") whose .parentNode === myDiv), and obviously not ideal if you're trying to support one code path that really just wants to take an arbitrary selector string as input and a list of matches as output! But if like me you ended up asking this question simply because you got stuck thinking "all you had was a hammer" don't forget there are a variety of other tools the DOM offers too.

这篇关于使用 querySelectorAll 检索直接子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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