DOM: NodeList vs HTMLCollection

By Xah Lee. Date: . Last updated: .

What is NodeList, HTMLCollection

NodeList and HTMLCollection are collection of Nodes. They are returned by many DOM methods.

Difference Between NodeList vs HTMLCollection

NodeList may include text node, or Whitespace Nodes, and other Node Type.

HTMLCollection only contains Node Type of element.

NodeList may or may not be Live Object. e.g. document.querySelectorAll is non-live. document.getElementsByName is live. There's no builtin way to find out whether NodeList is live object.

HTMLCollection is always a Live Object.

How to Determine NodeList or HTMLCollection

You can find out the type by:

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

It'll return a string like "[object HTMLCollection]" or "[object NodeList]".

γ€”see Determine Type of Object〕

Code to Verify

// print info of a object, see if they are true array, or iterable.
// version 2024-08-01

const f_print_info = (x) => {
  console.log("Type is:", Reflect.apply(Object.prototype.toString, x, []));
  console.log("is true array:", Array.isArray(x));
  console.log("has forEach:", Reflect.has(x, "forEach"));
  console.log("is iterable:", Reflect.has(x, Symbol.iterator));
};

f_print_info(document.getElementsByTagName("div"));
f_print_info(document.querySelectorAll("*"));
HTMLCollection vs NodeList 2024-08-01
HTMLCollection vs NodeList 2024-08-01

JavaScript DOM, About Node, Node Type

Basic DOM Element Methods