Trigger click in Typescript - Property 'click' does not exist on type 'Element'

Viewed 86246

I would like to trigger a click event on a HTML element in Typescript/Reactjs.

let element: Element = document.getElementsByClassName('btn')[0];
element.click();

The code above does work. But I'm getting a Typescript error:

ERROR in [at-loader] ./src/App.tsx:124:17
TS2339: Property 'click' does not exist on type 'Element'.

So what would be the correct way to do this?

6 Answers

Correct (type safe) way is:

if (element instanceof HTMLElement) {
  element.click();
}

You shouldn't use forced casts (as suggested by other answers) unless you really need them.

document
  .querySelectorAll<HTMLElement>('.ant-table-row-expand-icon')
  .forEach(node => node.click())

Use Like this

(<HTMLElement>document.getElementsByClassName('btn')[0]).click()

had a similar issue while scripting using Puppeteer , the following helped to resolve the type: srcTracker:HTMLElement

page.$eval(this.selectorElement,(srcTracker:HTMLElement) => srcTracker.click());

Related