JS 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("*"));
JS DOM, About Node, Node Type
Basic DOM Element Methods
- JS DOM: Node, Node Type, Element
- JS DOM: Get Element by ID, Name, Class etc
- JS DOM: Get Current Script Element
- JS DOM: Get Element Parent, Child, Sibling
- JS DOM: NodeList vs HTMLCollection
- JS DOM: Iterate HTMLCollection
- JS DOM: Element Attribute Methods
- JS DOM: Class Attribute (get add remove toggle)
- JS DOM: Create Element, Clone
- JS DOM: Insert, Remove, Replace Element
- JS DOM: insert Adjacent Element
- JS DOM: appendChild
- JS DOM: textContent, innerHTML, innerText, nodeValue
- JS DOM: Remove Element
- JS DOM: Remove All Children
- JS DOM: Change Element Content
- JS DOM: Add, Remove Event Handler