Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate a click on 'a' element using javascript/jquery

I am trying to simulate a click on on an element. HTML for the same is as follows

<a id="gift-close" href="javascript:void(0)" class="cart-mask-close p-abs" onclick="_gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);" rel="coupon">&nbsp;</a> 

How can i simulate a click on it. I have tried

document.getElementById("gift-close").click();

But its not doing anything

like image 533
user2373137 Avatar asked Jul 10 '13 11:07

user2373137


People also ask

Can you simulate a click in JavaScript?

Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.

How do you click an element in JavaScript?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

How do you simulate a click in HTML?

click() The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event.

What is click in jQuery?

jQuery click() MethodThe click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.


2 Answers

Using jQuery: $('#gift-close').trigger('click');

Using JavaScript: document.getElementById('gift-close').click();

like image 100
André Dion Avatar answered Oct 17 '22 08:10

André Dion


Using jQuery:

$('#gift-close').click();
like image 25
Alex Guerra Avatar answered Oct 17 '22 10:10

Alex Guerra