92

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?

8 Answers 8

171

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();
Sign up to request clarification or add additional context in comments.

4 Comments

or even HTMLButtonElement if you know it's a <button/>
Nope: ERROR in [at-loader] ./src/Game.tsx:123:13 TS2322: Type 'Element' is not assignable to type 'HTMLElement'. Property 'accessKey' is missing in type 'Element'.
Use cast operator document.getElementsByClassName('btn')[0] as HTMLElement
Thanks that was it! Didn't know that I could cast types like that. Gives me the Java feeling :o)
31

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.

Comments

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

3 Comments

Explain it please!
Only way it worked!
Yep. Nothing worked except this.
4

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

1 Comment

initEvent is not standard any more.
4

Use Like this

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

Comments

2

Modern syntax:

document.querySelector<HTMLElement>('.btn')?.click()

Comments

1

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

Comments

0

as mentioned here, also

var buttons = document.getElementsByClassName(
  "btn"
) as HTMLCollectionOf<HTMLElement>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.