Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't document.getElementsBy__ methods return an HTMLCollection?

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 HTMLCollections 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.

— W3C on collections

A couple places HTMLCollection is already being used:

document.images
element.children

NB: querySelectorAll returns a non-live NodeList.

like image 319
Web_Designer Avatar asked Mar 04 '14 21:03

Web_Designer


1 Answers

HTMLCollection was largely only included in the DOM spec to document how most browsers worked before the DOM was introduced. It only makes sense in the context of HTML, whereas the DOM was built to work consistently for both HTML and XML. Implementations of the DOM are allowed to omit HTMLCollection and all its uses and still be considered conforming; browsers have chosen to keep it to maintain backwards-compatibility with old websites.

like image 105
Telic Avatar answered Oct 24 '22 18:10

Telic