Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  151] [ 7]  / answers: 1 / hits: 101259  / 7 Years ago, wed, september 13, 2017, 12:00:00

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?


More From » reactjs

 Answers
13

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

[#56489] Monday, September 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;