问题描述
我正在尝试制作一个适用于多个页面的 js 代码.我正在尝试使用 querySelectorAll() 从 DOM 中获取元素.
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.
我需要订购元素.为此,我可以使用 xPath 或选择器(我更喜欢使用选择器,但 xPath 也可以).问题是:
querySelectorAll() 返回的 NodeList 中的元素是否按照标签在 HTML 中出现的顺序排列?
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?
注意:我想添加标签:querySelectorAll
Note: I'd like to add the tag: querySelectorAll
推荐答案
返回的节点列表是有序的.快速测试证明了这一点:
The returned node list is ordered. A quick test proved it:
document.querySelectorAll("body, head")[0]; //Returned [object HTMLHeadElement]
显然,<head>
标签出现在 HTML 文档中的 <body>
之前.NodeList 的第一个元素也是 <head>
元素,即使选择器在 `head 之前显示 body
.
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.
来自 http://www.w3.org/TR/selectors-api/#queryselectorall:
NodeSelector 接口上的 querySelectorAll()
方法必须,当调用,返回一个包含所有匹配元素的 NodeList节点子树中的节点,按文档顺序.如果没有此类节点,该方法必须返回一个空的 NodeList.
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.
这篇关于使用 querySelectorAll().方法返回的结果是否有序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!