How reliable is the "order" in the requested NodeLists

I have been interested about this topic for quite some time. These methods are as follows:

  • getElementsByTagName
  • getElementsByClassName
  • getElementsByName
  • querySelectorAll

As far as I know, these DOM methods are the only methods that can return frozen or live NodeLists . For some of these methods, the order is determined by the W3C specification. For example, http://www.w3.org records the following for NodeLists returned by querySelectorAll

The querySelectorAll () methods in the document, DocumentFragment, and Element Interfaces should return a NodeList containing all matching element nodes in the node context subtrees in the document order. If there are no matching nodes, the method should return an empty NodeList.

However, I could not find similar clear specifications for the other methods that I mentioned. My questions are here:

  • Is there a specific order (most likely document order) for the results?
  • how reliable and cross-browser are these specifications?

Absolutely clear:

 <div>this</div> <div>is</div> <div>a demo</div> // is this always guaranteed to be "<div>is</div>" document.querySelectorAll('div')[1] 
+7
source share
1 answer

Yes. All are in order / wood order.

  • getElementsByName ( DOM Level-2-HTML ) returns NodeList
  • querySelectorAll ( selectors API ) returns NodeList "in document order
  • getElementsByTagName ( DOM ) returns an HTMLCollection
  • getElementsByClassName ( DOM ) returns an HTMLCollection

HTMLCollection s and NodeList s are both listed as

items are sorted in tree order .

when they are available through indexes.

I think that these specifications (although related versions may be newer than some implementations) are reliably implemented by all browsers, mainly because the order of the tree is the most logical and simple in code. However, you may need to make sure that some browsers can return lists consisting of different elements, because their node mapping is different. I could come up with some quirks when determining the name element.

+4
source

All Articles