Reputation: 3135
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?
Upvotes: 90
Views: 128866
Reputation: 13298
Modern syntax:
document.querySelector<HTMLElement>('.btn')?.click()
Upvotes: 0
Reputation: 1075
as mentioned here, also
var buttons = document.getElementsByClassName(
"btn"
) as HTMLCollectionOf<HTMLElement>;
Upvotes: 0
Reputation: 3979
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());
Upvotes: 1
Reputation: 932
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.
Upvotes: 30
Reputation: 391
document
.querySelectorAll<HTMLElement>('.ant-table-row-expand-icon')
.forEach(node => node.click())
Upvotes: 19
Reputation: 1267
Use Like this
(<HTMLElement>document.getElementsByClassName('btn')[0]).click()
Upvotes: 4
Reputation: 68675
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();
Upvotes: 169
Reputation: 12103
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);
Upvotes: 4