使用querySelectorAll检索直接子项 [英] Using querySelectorAll to Retrieve Direct Children
问题描述
我可以这样做:
< div id =myDiv> ;
< div class =foo>< / div>
< / div>
myDiv = getElementById( myDiv);
myDiv.querySelectorAll(#myDiv> .foo);
也就是说,我可以成功地检索 myDiv
。
问题是,必须在选择器中包含 #myDiv
,因为我在 myDiv
元素上运行查询冗余)。
我应该能够离开 #myDiv
,但是选择器不合法语法,因为它以>
开头。
有人知道如何写一个选择器,选择器运行的元素的子元素?
好问题,但是你看到没有办法组合树根查询作为 John Resig命名它们。
但是,在某些情况下,您可以跳过 .querySelectorAll
并使用其他良好的老式DOM API功能。除了不支持的 myDiv.querySelectorAll(> *)
,您只需输入 myDiv.children
。
不幸的是,我不能想办法处理你的情况,而不添加更多的自定义过滤器逻辑(例如find myDiv.getElementsByClassName )
的 .parentNode === myDiv
),显然不是理想的,如果你试图支持一个代码路径,取任意选择器字符串作为输入,并将匹配列表作为输出!但是如果和我一样,你最终只是问这个问题,因为你被困在所有你是一个锤子不要忘记有各种各样的其他工具DOM。 >
I am able to do this:
<div id="myDiv">
<div class="foo"></div>
</div>
myDiv = getElementById("myDiv");
myDiv.querySelectorAll("#myDiv > .foo");
That is, I can successfully retrieve all the direct children of the myDiv
element that have class .foo
.
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).
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?
Good question, but as you see there is no way to do "combinator rooted queries" as John Resig names them.
However, in some cases you can just skip .querySelectorAll
and use other good old-fashioned DOM API features. Instead of the unsupported myDiv.querySelectorAll("> *")
you can just write myDiv.children
, for example.
Unfortunately I can't think of a 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屋!