Skip to content Skip to sidebar Skip to footer

Type 'NodeListOf' Is Not Assignable To Type 'Element[]'

let li: Element[] = document.getElementsByTagName('span'); I get the type conversion error, how to store the values in 'Element[ ]' ??

Solution 1:

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

Solution 2:

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')]

Solution 3:

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)

Post a Comment for "Type 'NodeListOf' Is Not Assignable To Type 'Element[]'"