DOM: History of GetElementsByClassName

By Xah Lee. Date: . Last updated: .
,

What Does getElementsByClassName Return?

As of 2019-05-30, on Google Chrome, Safari, Firefox:

// check get element functions return node list or html collection

console.log(
  Reflect.apply(
    Object.prototype.toString,
    document.getElementsByTagName("div"),
    [],
  ),
);

console.log(
  Reflect.apply(
    Object.prototype.toString,
    document.getElementsByClassName(""),
    [],
  ),
);

console.log(
  Reflect.apply(Object.prototype.toString, document.getElementsByName(""), []),
);

console.log(
  Reflect.apply(Object.prototype.toString, document.querySelectorAll("*"), []),
);
dom get element type 2024-08-01 NWBnT
dom get element type 2024-08-01 NWBnT

As of 2013-04-26, getElementsByClassName in {Firefox, Internet Explorer} return HTMLCollection. {Chrome, Safari, Opera} return NodeList. Older versions of Firefox returns NodeList.

As of 2016-07-02, getElementsByClassName in {Google Chrome, Firefox} returns HTMLCollection.

As of 2019-05-30, getElementsByClassName in {Google Chrome, Safari, Firefox} returns HTMLCollection.

Even Browsers and W3C Are Confused

Here is what Mozilla says:

Note: While the W3C DOM 3 Core specification says elements is a NodeList that was simply because of a an attempt to have the β€œcore” specification not depend on the β€œhtml” specification at that time. The DOM 4 draft says that elements is an HTMLCollection.

Gecko/Firefox currently returns a NodeList (Bug 162927) but starting with Gecko/Firefox 19, this method will return HTMLCollection (Bug 799464). Internet Explorer returns a HTMLCollection. WebKit returns a NodeList. Opera also returns a NodeList, but with a namedItem method implemented, which makes it similar to a HTMLCollection.

, from https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName

Here is WHATWG says as of 2016-07-02:

Elements is the better solution for representing a collection of elements. HTMLCollection is an historical artifact we cannot rid the web of.

Node and Element, Spec as of 2022-08-21

html spec node tree 2022-08-21
html spec node tree 2022-08-21
html spec old style collection 2022-08-21
html spec old style collection 2022-08-21
html spec NodeList 2022-08-21
html spec NodeList 2022-08-21
html spec HTMLCollection 2022-08-21
html spec HTMLCollection 2022-08-21

JavaScript DOM, About Node, Node Type