Prasanna
Prasanna

Reputation: 11

type 'NodeListOf<HTMLLIElement>' 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[ ]' ??

Upvotes: 1

Views: 13700

Answers (3)

Jason Mullings
Jason Mullings

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

Diullei
Diullei

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

gyre
gyre

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

Related Questions