使用querySelectorAll()。订购的方法返回的结果是? [英] Using querySelectorAll(). Is the result returned by the method ordered?
问题描述
我正在尝试制作适用于多个页面的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 :
querySelectorAll()$当
被调用时,NodeSelector接口上的c $ c>方法必须返回一个NodeList,其中包含节点子树中所有匹配的Element
节点,按文档顺序。如果没有
这样的节点,该方法必须返回一个空的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()。订购的方法返回的结果是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!