Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - Using querySelectorAll(). Is the result returned by the method ordered?

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.

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?

Note: I'd like to add the tag: querySelectorAll

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The returned node list is ordered. A quick test proved it:

document.querySelectorAll("body, head")[0]; //Returned [object HTMLHeadElement]

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.

From http://www.w3.org/TR/selectors-api/#queryselectorall:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...