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

JavascriptReactjsTypescript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Use the type HTMLElement instead of Element. HTMLElement inherits from Element. And in the documentation you can find that click function is defined in the HTMLElement.

Cast your element into the HTMLElement via

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

Use Like this

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

Solution 5 - Javascript

You should use ref to access DOM.

<button  ref={button => this.buttonElement = button} />
In your event handler:

this.buttonElement.click();// trigger click event

Or,Create HtmlEvents and attach to dom element.

var event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
var button = document.getElementsByClassName('btn')[0];
button.dispatchEvent(event);

Solution 6 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlorisView Question on Stackoverflow
Solution 1 - JavascriptSuren SrapyanView Answer on Stackoverflow
Solution 2 - Javascriptfo_View Answer on Stackoverflow
Solution 3 - JavascriptArmy-UView Answer on Stackoverflow
Solution 4 - JavascriptMukeshView Answer on Stackoverflow
Solution 5 - JavascriptVedView Answer on Stackoverflow
Solution 6 - JavascriptAlferd NobelView Answer on Stackoverflow