How to detect HTMLCollection/NodeList in JavaScript/Typescript?
How to detect HTMLCollection/NodeList in JavaScript/Typescript?
Detecting HTML Collection or NodeList in typescript.
HTMLCollection Detect
// check if variable is instance of HTMLCollection
HTMLCollection.prototype.isPrototypeOf(variable)
NodeList Detect
// check if variable is instance of NodeList
NodeList.prototype.isPrototypeOf(variable)
Typescript Comparator Example
let loaders: NodeListOf<Element> | HTMLCollectionOf<Element>;
loaders = document.getElementsByClassName("className"); // will return typeof HTMLCollectionOf<Element>
loaders = document.querySelectorAll("[class*='className']"); // will return typeof NodeListOf<Element>
if (HTMLCollection.prototype.isPrototypeOf(this.loaders)) {
console.log('loaders is instanceof HTMLCollection');
} else if (NodeList.prototype.isPrototypeOf(this.loaders)) {
console.log('loaders is instanceof NodeList');
}
Typescript how to iterate Nodelist or HTMLCollection variable type
Wrong/Bad
loaders.forEach((el) => {
console.log(el);
});
codes above will thrown:
Property 'forEach' does not exist on type
NodeListOf<Element> | HTMLCollectionOf<Element>
.Property 'forEach' does not exist on type
HTMLCollectionOf<Element>
. ts(2339)
Good
let loaders: NodeListOf<Element> | HTMLCollectionOf<Element>;
loaders = document.getElementsByClassName("className"); // will return typeof HTMLCollectionOf<Element>
loaders = document.querySelectorAll("[class*='className']"); // will return typeof NodeListOf<Element>
for (let index = 0; index < loaders.length; index++) {
const element: Element = loaders.item(index); // or loaders[index]
console.log(element);
}