DOM: NodeList vs HTMLCollection
What is NodeList, HTMLCollection
NodeList
and HTMLCollection
are collection of Nodes.
They are returned by many DOM methods.
- Both are Iterable Objects. (since JS2015)
- Both are Array-Like Objects.
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("*"));
JavaScript DOM, About Node, Node Type
Basic DOM Element Methods
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Get Element Parent, Child, Sibling
- DOM: NodeList vs HTMLCollection
- JS: Iterate HTMLCollection
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element Content
- JS: Add, Remove Event Handler