Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 432
brunoais Avatar asked Nov 20 '11 18:11

brunoais


People also ask

Does querySelectorAll return in order?

The querySelectorAll() methods on the Document , DocumentFragment , and Element interfaces must return a NodeList containing all of the matching Element nodes within the subtrees of the context node, in document order. If there are no matching nodes, the method must return an empty NodeList .

What does the querySelectorAll () method do?

The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.

Which type of objects does the querySelectorAll return?

The querySelectorAll() method returns all elements that matches a CSS selector(s). The querySelectorAll() method returns a NodeList.

Does querySelectorAll returns an array?

The querySelectorAll method returns an array-like object called a node list. These data structures are referred to as “Array-like”, because they appear as an array, but can not be used with array methods like map and forEach .


1 Answers

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.

like image 200
Rob W Avatar answered Oct 08 '22 21:10

Rob W