Search code examples
jquerydomjquery-selectorssizzleselectors-api

Sizzle and/or querySelectorAll - order of enumeration for nested elements?


If I have a nested set of DOM elements, e.g. ul > li > ul > li and I use the selector li by itself, do either Sizzle or document.querySelectorAll define the order in which the elements will be returned?

Orderings that might be returned include "top most first", "leaf nodes first", or just "in document order", but I've never seen anything written down to specify which.


Solution

  • Well, it's quite clearly said in MDN documentation for document.querySelectorAll:

    Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors.

    W3 DOM documentation gives the same description:

    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. [...] The term 'document order' means a depth-first pre-order traversal of the DOM tree or subtree in question.

    In other words, given the following structure:

    <div class="a">
      <div class="a-a">
        <div class="a-a-a"></div>    
        <div class="a-a-b"></div>
      </div>
      <div class="a-b">
        <div class="a-b-a"></div>    
        <div class="a-b-b"></div>
      </div>
    </div>
    <div class="b">
      <div class="b-a">
        <div class="b-a-a"></div>    
        <div class="b-a-b"></div>
      </div>
      <div class="b-b">
        <div class="b-b-a"></div>    
        <div class="b-b-b"></div>
      </div>
    </div>
    

    ... result of document.querySelectorAll('div') should be a NodeList of exactly the following order:

    ["a", "a-a", "a-a-a", "a-a-b", "a-b", "a-b-a", "a-b-b", 
     "b", "b-a", "b-a-a", "b-a-b", "b-b", "b-b-a", "b-b-b"]