Why don't getElementsByName
, getElementsByTagName
, and getElementsByClassName
return an HTMLCollection
(W3C, MDN) instead of a NodeList
(W3C, MDN)?
All three return a live NodeList of only elements:
document.getElementsByName('nameAttrVal');
document.getElementsByTagName('div');
document.getElementsByClassName('space separated classes');
NodeLists are great, but HTMLCollection
s are more specific as they can only contain HTML elements. It seems like this would be perfect for those methods.
When a collection is created, a filter and a root are associated with the collection.
For example, when the HTMLCollection object for the document.images attribute is created, it is associated with a filter that selects only img elements, and rooted at the root of the document.
The collection then represents a live 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.
A couple places HTMLCollection
is already being used:
document.images
element.children
NB: querySelectorAll
returns a non-live NodeList
.
qSA
was defined a few years after those three APIs, so I think the spec designers agree with you. But you can't go back and change things now. – Davon