I am wondering about this topic for quite a while. The methods in question are the following:
getElementsByTagName
getElementsByClassName
getElementsByName
querySelectorAll
As far as I know, those DOM methods are the only methods which are able to return frozen or live NodeLists
. For some of those methods, order is defined by W3C spec. For instance, http://www.w3.org writes the following for NodeLists
returned by querySelectorAll
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.
However, I couldn't find similar clear specifications for the the other methods I mentioned. My questions here are:
- is there a defined order (most likely document order) for the results ?
- how reliable and cross-browser implemented are those specs ?
To be absolute clear:
<div>this</div>
<div>is</div>
<div>a demo</div>
// is this always guaranteed to be "<div>is</div>"
document.querySelectorAll('div')[1]