
Eslint Prettier In Typescript Project Using Vscode
2021-11-28 / Dimas Lanjaka
How to detect HTMLCollection/NodeList in JavaScript/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);
}Eslint Prettier In Typescript Project Using Vscode
PermaLink: https://www.webmanajemen.com/NodeJS/ts-detect-nodelist-or-htmlcollections.html
Google Rich Snippets | Schema Markup Validator | Google Pagespeed Insight