Clicking on a Link using jQuery

Well to me it’s easier to do it with JavaScript but today one of my friends was trying to click on a link on his page using jQuery and he came to me complaining that the click() function is not working.

The problem with his code was that when he was selecting his a with jQuery the result that comes out is an array so you need to specify which item of the array to process. well selecting a single item will always result an array with 1 key and a value which means using [0] is the solution.

Below is the sample code of clicking on a link using jQuery:

<html>
<head>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
</head>
<script>
$(document).one( "click", function() {
  $('#link')[0].click();
});
</script>
<body>
  <a href="https://hazaveh.net" id="link" target="_blank">Hazaveh</a>
</body>
</html>

in the code above after selecting the element with id “link” you need to make sure to tell jquery that which one of the items of the selected array you wish to click or process.

Please note in my code I also used function one() which means to do this job only once.

Leave a Reply