type 'NodeListOf' is not as

2019-09-15 10:50发布

let li: Element[] = document.getElementsByTagName('span');

I get the type conversion error, how to store the values in 'Element[ ]' ??

3条回答
该账号已被封号
2楼-- · 2019-09-15 11:26

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);
查看更多
劫难
3楼-- · 2019-09-15 11:42

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)
查看更多
时光不老,我们不散
4楼-- · 2019-09-15 11:50

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')]
查看更多
登录 后发表回答