Sometimes, we want to programmatically click on an element in JavaScript.
In this article, we’ll look at how to programmatically click on an element in JavaScript.
How to programmatically click on an element in JavaScript?
To programmatically click on an element in JavaScript, we can create a mouse event object and call dispatchEvent
.
For instance, we write
const clickEvent = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: false,
});
element.dispatchEvent(clickEvent);
to create the MouseEvent
object that does a click.
We set the bubbles
option to true
to make it propagate to the parent.
cancelable
set to false
means it’s not cancelable.
Then we call element.dispatchEvent
with clickEvent
to trigger a click event on the HTML element
.
Conclusion
To programmatically click on an element in JavaScript, we can create a mouse event object and call dispatchEvent
.