Reputation: 11
let li: Element[] = document.getElementsByTagName('span');
I get the type conversion error, how to store the values in 'Element[ ]' ??
Upvotes: 1
Views: 13700
Reputation: 1004
Try creating the implicit form of the variable first, then transfer this definition explicitly:
let li = document.getElementsByTagName('span');//Hover IDE
To..
let li: NodeListOf<HTMLSpanElement>= document.getElementsByTagName('span');
Then..
let arr: Element[]
for (let i in li)
arr.push(li[i] as Element)
Upvotes: 0
Reputation: 12414
The object returned from document.getElementsByTagName('span')
is not compatible with an array object. You need to declare it as following:
let li: NodeListOf<HTMLElement> = document.getElementsByTagName('span');
If you really need this to be an array object you can use:
let li: NodeListOf<HTMLElement> = document.getElementsByTagName('span');
let liArray: Element[] = Array.prototype.slice.call(li);
Upvotes: 6
Reputation: 16777
The problem here is that getElementsByTagName
returns an array-like object, not an actual array. You need to coerce it to one first using the spread operator (or [].slice.call(...)
for ES5):
let li: HTMLElement[] = [...document.getElementsByTagName('span')]
Upvotes: 1