Ben Racicot
Ben Racicot

Reputation: 5934

Focus a NodeList element

NodeList items do not have a focus method. However, I've seen a few articles written with literally nodeList[index].focus() which must be incorrect, right?

How do we focus the element from a NodeList?

let nodeList:NodeList = el.nativeElement.querySelectorAll('a');
...
nodeList[0].focus(); // Property 'focus' does not exist on type 'Node'
(nodeList[0] as HTMLElement).focus(); // doesn't work

Upvotes: 2

Views: 1005

Answers (1)

Nick
Nick

Reputation: 16576

NodeList is not an narrow enough type; you have to specify that it's a node list of HTMLElements. You can do this with the NodeListOf<HTMLElement> type:

let nodeList: NodeListOf<HTMLElement> = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();

Note that you could alternatively let the compiler infer the correct type of nodeList and avoid having to explicitly type it:

let nodeList = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();

Upvotes: 2

Related Questions