Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does getElementsByClassName keep ordering?

Tags:

javascript

The webpage I am working with contains an alphabetically sorted list of div's that all have the same class. If I call document.getElementsByClassName('classname'), can I be sure that the array it returns will be sorted in HTML order?

like image 564
Yay295 Avatar asked Jan 09 '23 00:01

Yay295


2 Answers

Yes.

The collection then represents a view of the subtree rooted at the collection’s root, containing only nodes that match the given filter. The view is linear. In the absence of specific requirements to the contrary, the nodes within the collection must be sorted in tree order.

— https://dom.spec.whatwg.org/#old-style-collections

like image 61
Quentin Avatar answered Jan 17 '23 20:01

Quentin


I found following statement in "The WHATWG Blog":

The getElementsByClassName(classNames) method takes a string that contains an unordered set of unique space-separated tokens representing classes. When called, the method must return a live NodeList object containing all the elements in the document, in tree order, that have all the classes specified in that argument, having obtained the classes by splitting a string on spaces. If there are no tokens specified in the argument, then the method must return an empty NodeList. If the document is in quirks mode, then the comparisons for the classes must be done in an ASCII case-insensitive manner, otherwise, the comparisons must be done in a case-sensitive manner.

https://blog.whatwg.org/tag/getelementsbyclassname

like image 31
Vlad DX Avatar answered Jan 17 '23 21:01

Vlad DX