3

I know that live NodeList returned by getElementsByTagName preserves the document order of elements.

Is it true for getElementsdByClassName, getElementsByName and querySelectorAll methods?

does these method also preserve the document order?

Any DOM/HTML5 W3C standard link would be appreciated.

P K
  • 9,972
  • 12
  • 53
  • 99
  • exact duplicate of [How reliable is "order" in queried NodeLists](http://stackoverflow.com/questions/13102517/how-reliable-is-order-in-queried-nodelists) – Bergi Apr 11 '13 at 14:23

2 Answers2

2

No, they don't all work the same way. Only the getElementsByTagName method returns a live collection.

The getElementsByTagName method returns a NodeList object which is a live collection of elements.

The querySelectorAll method returns a NodeList object which is not a live collection.

The getElemendsByClassName and getElementsByName methods returns a HTMLCollection object which is not a live collection.

(Note that different documentation for getElemenetsByName specifies either a HTMLCollection or a NodeList.)

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • thanks, I am more interested about document order not live or static – P K Apr 11 '13 at 13:40
  • @PK: All methods return nodes in tree order. – Guffa Apr 11 '13 at 14:12
  • @Guffa - Where does it specify that HTMLCollection is not live? A quick test on getElementsByName suggests that it does return a live collection, at least on FF, Chrome and IE10. – Alohci Apr 11 '13 at 15:21
  • [WhatWG DOM](http://dom.spec.whatwg.org/#concept-collection) says that a HTMLCollection is a collection that "can be either live or static. Unless otherwise stated, a collection must be live". I can't find anywhere where it states that an API function returns a static collection. – Alohci Apr 11 '13 at 15:28
  • ... except querySelectorAll – Alohci Apr 11 '13 at 15:35
2

Yes. All of them are in document order / tree order.

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

HTMLCollections and NodeLists are both specified to have

the elements are sorted in tree order.

when those are accessed via indizes. It does not really matter whether the NodeList is live or not (though of course the actual document order could change in contrast to the one preserved in the static NodeList).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375