free html hit counter
HTMLCollection/NodeList in JavaScript/Typescript?
HTMLCollection/NodeList in JavaScript/Typescript?
2021-11-28 / Dimas Lanjaka

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);
}

HTMLCollection/NodeList in JavaScript/Typescript?

PermaLink: https://www.webmanajemen.com/NodeJS/ts-detect-nodelist-or-htmlcollections.html
Incoming search terms for HTMLCollection/NodeList in JavaScript/Typescript?:
  • HTMLCollection/NodeList in JavaScript/Typescript?
  • HTMLCollection/NodeList in JavaScript/Typescript? NodeJS
  • typescript
  • NodeListOf
  • HTMLCollectionOf

Google Rich Snippets | Schema Markup Validator | Google Pagespeed Insight