Sending a parent anchor click event

How to send a click event (JS or JQuery) to a parent object that is an anchor? My main HTML looks like this:

<a href="javascript:myFunc(1,2,3)"> <img id="btn1" src="myimg.png"> </a> 

Therefore, I can easily reference the bind button via:

 document.getElementById('btn1').parentNode 

but

 document.getElementById('btn1').parentNode.click 

although it doesn't seem to cause a console error on firebug, the javascript function doesn't seem to work either. How to send a click on this thing. By the way, I have no control over HTML, so I can’t just declare the identifier of the attached tag.

+4
source share
4 answers

Gone are the days when you can use href="javascript:blah" , especially if you use the jQuery, Dojo, ExtJs library or the rest. Event handlers should always be attached outside of HTML.

 $(function() { $("#btn1").click(function() { $(this).parent().click(); }; }); 

Here is a snippet that you can test on SO pages (copy + paste in Firebug)

 $("#hlogo a").click(function() { alert("a!"); return false; }); $("#hlogo a img").click(function() { alert("img!"); $(this).parent().click(); }); 
+4
source

Normal links with normal href

 // assuming the link is always the immediate parent of #btn1 $("#btn1").parent().trigger("click"); 

Links with Javascript commands like HREF

In your case, I note that your HREF value is a call to the javascript function with parameters. For this, you can evaluate this HREF and not the link:

 // run the href-javascript from the parent anchor eval($("#btn1").parent().attr("href")); 

I created a test file and used firebug to try both methods. The first returns 1 , indicating that the link was clicked, but javascript is never executed. The second method actually executes the javascript found inside the HREF value of the link itself. This should be an adequate solution to your specific need.

0
source

EDIT: Ignore this answer as it is not suitable for links; see comments below.

The click property of a is a function property, just like a method; everything that you do refers to a property, not calls it.

 document.getElementById('btn1').parentNode.click(); 

(pay attention to () to call the method call), but if you use jQuery, then Jonathan Sampson's answer will do what you need - it makes no sense to load the library, and then not use it :-)

Although Jonathan's answer may be shortened as jQuery provides a click method :

 $("#btn1").parent().click(); 
0
source

A jQuery example could be as follows:

 $(event.target).closest('a').trigger('click') 

or in your words something like this

 $('#bth1').closest('a').trigger('click') 
0
source

All Articles