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

2

11

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.

Agnesse answered 4/3, 2014 at 21:55 Comment(5)
Well 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
Potential duplicate question - LINKEntrance
@Quinn, I'm not sure that it's a duplicate exactly, but it's certainly relevant.Semang
Try https://mcmap.net/q/276072/-create-a-htmlcollectionBoxwood
Check out NodeList.jsRichierichlad
J
2

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.

Janeejaneen answered 24/3, 2014 at 7:38 Comment(0)
B
-2

Because can exist more tags html elements with same name or class name, and you can manipulate it as DOM object, not as html type

"Returns the first item with ID or name name from the collection". W3C

If you try catch a event or modify it like as add attributes in a specific node you can do it selected by Id or name collection

Benefactress answered 5/3, 2014 at 1:16 Comment(1)
I'm not sure what you mean? Could you clarify?Agnesse

© 2022 - 2024 — McMap. All rights reserved.