問(wèn)題描述
我正在嘗試制作一個(gè)適用于多個(gè)頁(yè)面的 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.
我需要訂購(gòu)元素.為此,我可以使用 xPath 或選擇器(我更喜歡使用選擇器,但 xPath 也可以).問(wèn)題是:
querySelectorAll() 返回的 NodeList 中的元素是否按照標(biāo)簽在 HTML 中出現(xiàn)的順序排列?
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?
注意:我想添加標(biāo)簽:querySelectorAll
Note: I'd like to add the tag: querySelectorAll
推薦答案
返回的節(jié)點(diǎn)列表是有序的.快速測(cè)試證明了這一點(diǎn):
The returned node list is ordered. A quick test proved it:
document.querySelectorAll("body, head")[0]; //Returned [object HTMLHeadElement]
顯然,<head>
標(biāo)簽出現(xiàn)在 HTML 文檔中的 <body>
之前.NodeList 的第一個(gè)元素也是 <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.
來(lái)自 http://www.w3.org/TR/selectors-api/#queryselectorall:
NodeSelector 接口上的 querySelectorAll()
方法必須,當(dāng)調(diào)用,返回一個(gè)包含所有匹配元素的 NodeList節(jié)點(diǎn)子樹中的節(jié)點(diǎn),按文檔順序.如果沒有此類節(jié)點(diǎn),該方法必須返回一個(gè)空的 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.
這篇關(guān)于使用 querySelectorAll().方法返回的結(jié)果是否有序?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!