Mike Thrussell Mike Thrussell - 7 months ago 47
Javascript Question

.click() working with document.getElementById, but not with jquery selector

This works:

$(function() {
document.getElementById('click').click();
});


This doesn't:

$(function() {
$('#click').click();
});


Why?

EDIT: (for completeness sake; an answer has been reached):

$(function() {
$('#click').trigger('click')
});


also fails

Answer

Why?

Because jquery click method accepts a handler which will be called on click.

However, DOM click method simulates the click method itself.

You need to

$('#click')[0].click();

or trigger it

$('#click').trigger('click')
$('#click').click(); 

Last two will work only if there is a event-handler assigned. That is, it won't fire simple anchor click but onclick event will be invoked.

Here is the JS Fiddle

DEMO

function f1()
{
   document.getElementById("link1").click();
   document.getElementById("link2").click();
}

function f2()
{
   $("#link1").click();
   $("#link2").click();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:alert(1)" id="link1">Link 1 </a>
<a onclick="alert(2)" id="link2">Link 2 </a>

<button onclick="f1();">DOM click</button>

<button onclick="f2();">Jquery Click</button>