8

I am new to typescript and I'm trying to iterate over a HTMLCollection got by document.getElementsByClassName(). My code is:

let tag_list = document.getElementsByClassName("...") as HTMLCollectionOf<HTMLLinkElement>;
for (const tag of tag_list) {
    //do sth with tag.href
}

But it turns out that "TS2495: Type 'HTMLCollectionOf' is not an array type or a string type." So what is the best way I can do to prevent this error?

Evian
  • 1,035
  • 1
  • 9
  • 22

3 Answers3

12

HTMLCollectionOf<HTMLLinkElement> is not an array, therefore, you cannot iterate it. So, you need to make it an array

for (const tag of Array.from(tag_list)) {

Hope this help

Nguyen Phong Thien
  • 3,237
  • 1
  • 15
  • 36
1

As shown by this S.O. answer, it's compilation dependant.

tsconfig.json:

{
  "compileOnSave"  : true,
  "compilerOptions": {
    "noImplicitAny"   : true,
    "target"          : "ES2021",
    "moduleResolution": "Node"
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

The following code compiles and runs:

const tds = document.getElementsByTagName('td') as HTMLCollectionOf<HTMLTableCellElement>;
for( const td of tds ) {
  Utils.onClick( td, ( event: UIEvent ) => this.place( event, 1, 1 ));
}
Aubin
  • 14,617
  • 9
  • 61
  • 84
0

You can smash Typescript into thinking anything is any type by converting it to any first and then to the type you want, like this:

for (const child of dom.children as any as HTMLElement[]) {
  ....
}

Ugly but effective, this technique lets you "lie" to Typescript about a type. Since JavaScript will happily iterate over an HTMLElement's children, lying to Typescript like this lets JavaScript just do its thing.

Bill Burdick
  • 935
  • 10
  • 15