问题描述
我正在尝试制作一个适用于多个页面的 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]
显然, 标签出现在 html 文档中的 之前.nodelist 的第一个元素也是 元素,即使选择器在 `head 之前显示 body.
obviously, the tag appears before in a html document. the first element of the nodelist is also a 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.