views:

49

answers:

2

How would I retrieve the javascript call in the anchor tag below in JS or JQuery? Basically I want to get the code ("javascript:do_my_function('blah', 'string1', 1);") retrieved so I can execute it. This anchor is embedded several deep in some div tags as well.

<a onmouseout="swapImage('btn1','','http://img2.comp.com/img/buttons/btn_g.png',1)" onmousedown="swapImage('btn1','','http://img2.comp.com/img/buttons/btn_g_d.png',1)" onmouseover="swapImage('btn1','','http://img2.comp.com/img/buttons/btn_g_a.png',1)" href="javascript:do_my_function('blah', 'string1', 1);">
<img id="btn1" width="180" height="60" alt="" src="http://img2.comp.com/img/buttons/btn_ge.png"/&gt;
</a>
A: 

To retrieve it just use:

 var href = document.getElementById('btn1').parentNode.href;

That just finds the img by id, and grabs its parent, the a tag in question.

To call it, you can use:

 window.location = href;

Or you could parse it and eval() it. All of this is highly unconventional by the way. Do you not have any further control over the code?

Doug Neiner
The first part seems to work where I assign the href value to a variable. However, I have to strip out the leading "javascript:" string. The strange thing is that the eval(href) works when I execute it from the console in firebug but when I try to execute it in JS from the actual rendered page, I get an "undefined function" error. Doing the "window.location" fails because it seems it is trying to navigate to the JS function. I don't want to navigate away, just call the function.
GregH
A: 

To do it with jQuery you can do

var jscript = $('#btn1').parent().attr('href');
eval(jscript);

This is not a recommended way to do things. Changing the html would be much better

PetersenDidIt