21

Imagine there is an element #button1 on website which is watched by jQuery:

$('#button1').click(function(){
   console.log("you clicked");
};

So how do I click this #button1 element via JavaScript console? Is there a command like click("#button1")? Thanks.

Luka
  • 1,720
  • 3
  • 19
  • 29
user3719693
  • 215
  • 1
  • 2
  • 7
  • Possible duplicate of [How to trigger event in JavaScript?](http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript) – Sarbbottam Jul 26 '14 at 10:13

5 Answers5

63

You can trigger click functio like bellow

Using JQuery

$('#button1').click()

using simple JS

document.getElementById('button1').click();
Mritunjay
  • 24,184
  • 7
  • 51
  • 67
8

You can trigger a click by omitting the callback function:

$('#button1').click();
DF_
  • 3,565
  • 24
  • 33
5

You can not click, but simulate or trigger click. Please refer Creating and triggering events

Sarbbottam
  • 5,150
  • 3
  • 27
  • 39
  • Can you tell me what trigger should I use for this situation? I need to see an example, then I will get it. – user3719693 Jul 26 '14 at 10:14
  • If you are looking for ``vanilla javascript`` solution, please refer [Triggering built-in events](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events). If looking for ``jQuery`` solution, other flks have already posted the answer. – Sarbbottam Jul 26 '14 at 10:17
  • Upvoting because this clarification (you can simulate but NOT trigger) would be helpful to have near the top of the thread. – olisteadman Nov 08 '20 at 18:30
5

You can achieve this without jQuery:

document.getElementById("button1").click(); // clicks the button
chris97ong
  • 6,592
  • 7
  • 29
  • 49
4

You can also use this apart from the answers mentioned already:

$( "#button1" ).trigger( "click" );
V31
  • 7,598
  • 3
  • 25
  • 44