Programmatically click on an element in Javascript

January 23, 2019

In many situations you need to simulate a click on an element. Many times this is useful in testing, where you'd need to simulate a click and test the consequences of the action.

How to do it in jQuery:

// Click on a <button> element with ID of my-btn
$("button#my-btn").click(function(){
  console.log("Clicked");
});

In plain Javascript:

document.getElementById("my-btn").click();