使用 querySelectorAll()。方法返回的结果是有序的吗?

发布于 2024-12-17 06:16:17 字数 232 浏览 3 评论 0原文

我正在尝试编写一个适用于多个页面的js代码。 我正在尝试使用 querySelectorAll() 来获取 DOM 中的元素。

我需要订购元素。为此,我可以使用 xPath 或选择器(我更喜欢使用选择器,但 xPath 也可以)。问题是:
querySelectorAll() 返回的 NodeList 中的元素是否按照标签在 HTML 中出现的顺序排序?

注意:我想添加标签:querySelectorAll

I'm trying to make a js code that works with multiple pages.
I'm trying to use querySelectorAll() to obtain the elements form the DOM.

I need the elements to be ordered. In order to do that I may use xPath or selectors (I'd prefer to use selectors but xPath is also ok). The problem is:
Are the elements in the NodeList returned by querySelectorAll() ordered against the order that the tags appear in the HTML?

Note: I'd like to add the tag: querySelectorAll

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

握住你手 2024-12-24 06:16:17

返回的节点列表是有序的。快速测试证明了这一点:

document.querySelectorAll("body, head")[0]; //Returned [object HTMLHeadElement]

显然,在 HTML 文档中 标记出现在 之前。 NodeList 的第一个元素也是 元素,即使选择器在 `head 之前显示 body 也是如此。

来自http://www.w3.org/TR/selectors-api/#queryselectorall

NodeSelector 接口上的 querySelectorAll() 方法必须,当
调用时,返回一个包含所有匹配元素的 NodeList
节点子树中的节点,按文档顺序。如果没有
对于此类节点,该方法必须返回一个空的 NodeList。

The returned node list is ordered. A quick test proved it:

document.querySelectorAll("body, head")[0]; //Returned [object HTMLHeadElement]

Obviously, the <head> tag appears before <body> in a HTML document. The first element of the NodeList is also a <head> element, even if the selector shows body before `head.

From http://www.w3.org/TR/selectors-api/#queryselectorall:

The querySelectorAll() method on the NodeSelector interface must, when
invoked, return a NodeList containing all of the matching Element
nodes within the node’s subtrees, in document order. If there are no
such nodes, the method must return an empty NodeList.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文