79

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

Suraj Jain
  • 4,463
  • 28
  • 39
brunoais
  • 6,258
  • 8
  • 39
  • 59

1 Answers1

95

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 6
    I already tested with firefox, chrome and Opera. All of them showed them ordered but I just wanted to know if that happens in all browsers. – brunoais Nov 20 '11 at 18:50
  • 3
    That is a CSS selector. The seperation by ',' doesn't mean any order (that part is in the spec in the part about how the selectors select) – brunoais Nov 20 '11 at 18:52
  • @brunoais Have a look at the linked w3 specification. – Rob W Nov 20 '11 at 18:52
  • That quote is exactly what I wanted! That answers the question, thank you. (/me still wondering why he didn't find it when he searched) – brunoais Nov 20 '11 at 18:54
  • 15
    @brunoais Google search tips: Add "w3 spec" to your search query if you're looking for an official specification, and "mdn" if you're looking for a reliable source regarding CSS/JavaScript/HTML/... – Rob W Nov 20 '11 at 18:56
  • 5
    +1, but I would move the quote from the spec first, since the fact that one browser implementation at one time returned results in document order doesn't prove much. – Clément Jul 11 '21 at 03:53
  • what's "document order"? depth first or breadth first? – capr Feb 26 '22 at 09:53
  • 4
    @capr "The term **document order** means a depth-first pre-order traversal of the DOM tree or subtree in question" - https://www.w3.org/TR/selectors-api/#document-order – Michael T Jun 08 '22 at 08:45