有没有办法让 querySelectorAll 只搜索元素的子元素,而不是所有后代?
例如,如果我有一个文档片段:(
<div> <!-- I have a reference to this: "outerDiv". -->
<p> <!-- This is the <p> I want to select. -->
<div>
<p> <!-- I don't want to select this <p>. --> </p>
</div>
</p>
</div>
这是一个假设的文档。HTML 解析器实际上不会构建如下所示的 DOM。)
以及对最外层
的引用元素,我想以某种方式使用 outerDiv.querySelectorAll('p')
来仅选择作为外部元素直接子元素的
元素
我无法使用 outerDiv.childNodes
并搜索
元素,因为我实际上有一个比
"p"
长得多的选择器(例如,它可能看起来像"p > a > b"
)。我也无法控制 HTML,也无法使用 jQuery 或其他 JavaScript 库。
将 "div > "
添加到选择器并从 outerDiv.parentNode
应用它也是不够的,因为内部
也匹配
“div > p”
。
有没有一种干净的方法可以做到这一点,而不必自己过多地解析 CSS 选择器?
For example, if I have a snippet of a document:
<div> <!-- I have a reference to this: "outerDiv". -->
<p> <!-- This is the <p> I want to select. -->
<div>
<p> <!-- I don't want to select this <p>. --> </p>
</div>
</p>
</div>
(This is a hypothetical document. HTML parsers would not actually construct a DOM that looks like this.)
and a reference to the outermost <div>
element, I'd like to somehow use outerDiv.querySelectorAll('p')
to select only the <p>
elements that are direct children of the outer <div>
.
I can't use outerDiv.childNodes
and search for the <p>
elements because I actually have a selector that is much longer than "p"
(e.g., it might look like "p > a > b"
). I also don't have control over the HTML and can't use jQuery or other JavaScript libraries.
It's also not sufficient to prepend "div > "
to the selector and apply it from outerDiv.parentNode
since the inner <p>
also matches "div > p"
.
Is there a clean way to do this without having to parse the CSS selector myself, too much?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您有对外部 div 的引用,则可以使用以下表达式:
此表达式将选择作为outerDiv 元素的直接子元素的所有 p 元素,因为如developer.mozilla.org
(在下面的代码片段中,我没有使用带有段落的示例,因为将
div
或p
元素放入p
中是错误的检查以下链接:Stack Overflow & Mozilla 开发者)Supposing that you have a reference to the outer div you can use the below expression:
This expression will select all p elements that are direct children of outerDiv element because as referred on developer.mozilla.org
(in the following code snippet I dont use the example with paragraph because is wrong to put a
div
orp
element inside ap
element. Check these links about this: Stack Overflow & Mozilla Developer)你可以使用
body>吗?分区> p
或最外层 div 之外的任何内容?Can you use
body > div > p
or whatever lies outside of the outermost div?我建议您采用 Nick Pantelidis 的答案,但为了后代,这里有另一个可能的解决方案。
这使用 Element.matches 来测试选择器是否匹配每个特定的子元素(请记住,与
childNodes< /code>
,
子项
仅包含
Node.ELEMENT_NODE
节点):I recommend you go with Nick Pantelidis's answer, but just for posterity, here is another possible solution.
This uses Element.matches to test if the selector matches each specific child element (remember, unlike
childNodes
,children
only containsNode.ELEMENT_NODE
nodes):