Search code examples
javascripthtmltypescriptnodelist

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

Solution

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