問題描述
我正在嘗試制作一個適用于多個頁面的 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().方法返回的結果是否有序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!