Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 994
Floris Avatar asked Sep 13 '17 17:09

Floris


People also ask

How do you trigger a click element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How do I programmatically trigger click event in angular 6?

JS code: document. getElementById('mat-checkbox-1-input'). click();

Does not exist on type HTMLElement?

The error "Property 'X' does not exist on type 'HTMLElement'" occurs when we try to access a property that doesn't exist on an element of type HTMLElement . To solve the error, use a type assertion to type the element correctly before accessing the property.


2 Answers

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(); 
like image 127
Suren Srapyan Avatar answered Sep 20 '22 17:09

Suren Srapyan


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.

like image 28
fo_ Avatar answered Sep 24 '22 17:09

fo_