当使用querySelectorAll时,是否有一种方法来引用上下文节点的直接子节点,而不使用ID? [英] When using querySelectorAll, is there a way to reference the immediate children of the context node, without using IDs?

查看:149
本文介绍了当使用querySelectorAll时,是否有一种方法来引用上下文节点的直接子节点,而不使用ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个HTML结构,如

Say I have an HTML structure like

<div id="a">
  <div id="b">
    <div id="c"></div>
  </div>
</div>

要使用querySelectorAll查询a的子节点,我可以做

To do a query for the children of "a" using querySelectorAll I can do something like

//Get "b", but not "c"
document.querySelectorAll('#a > div')

我的问题是:可以在没有ID的情况下节点直接?我尝试了

My question is: is it possible to do this without the ID, referencing the node directly? I tried doing

var a_div = document.getElementById('a')
a_div.querySelectorAll('> div') //<-- error here

但我得到一个错误告诉我,使用的是无效的。

but I get an error telling me that the selector I used is invalid.

如果有人想知道,我的真实用例会更复杂。 foo .bar .baz',所以我宁愿避免手动DOM遍历。目前,我添加一个临时的id到根div,但似乎是一个丑陋的黑客...

And in case anyone is wondering, my real use case would be something more complicated like '> .foo .bar .baz' so I would prefer to avoid manual DOM traversal. Currently I am adding a temporary id to the root div but that seems like an ugly hack...

推荐答案

't a way (yet)引用某个元素的所有子元素,而不使用对该元素的引用。因为> 子组合器,表示父元素和子元素之间的关系,

No, there isn't a way (yet) to reference all childs of some element without using a reference to that element. Because > is a child combinator, which represents a relationship between a parent and child element, a simple selector (a parent) is necessary (which is missing in you example).

在注释中, BoltClock说 选择器API第2级规范定义了一种方法 findAll em>更改 ,其接受作为参数的可能被称为相对选择器(可以用组合器而不是复合选择器开始的选择器)

当实现时,它可以如下使用:

In a comment, BoltClock said that the Selectors API Level 2 specification defines a method findAllname may change "which accepts as an argument what will probably be known as a relative selector (a selector that can start with a combinator rather than a compound selector)".
When this is implemented, it can be used as follows:

a_div.findAll('> div');

这篇关于当使用querySelectorAll时,是否有一种方法来引用上下文节点的直接子节点,而不使用ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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