Typescript trigger click - The 'click' property does not exist in the 'Element' type

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

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

The above code works. But I get 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 right way to do this?

+11
source share
3 answers

Use HTMLElement instead of Element . HTMLElement is inherited from Element. And in the documentation, you may find that a function is defined in an HTMLElement. click

Pass your item to HTMLElement via

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

You must use refto access the DOM.

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

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

Or, create HtmlEvents and attach the dom element.

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

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

Source: https://habr.com/ru/post/1685624/


All Articles