Pull javascript code from tag using js or jQuery
-
11-09-2019 - |
Question
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"/>
</a>
Solution
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?
OTHER TIPS
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow