views:

1373

answers:

5

Hi,

Using jquery, I'd like to get the javascript from an A tag's onClick attribute.

<a href='#' onClick='alert("boo");' />

In Firefox: alert($('a').attr("onClick")) shows: alert("boo")

In IE 6/7: alert($('a').attr("onClick")) shows: function anonymous(){alert("boo");return false;}

How can I retrieve just the javascript, and not the wrapped function, in IE 6/7 using jquery? (or plain javascript)?

Franko

A: 

Have you tried :

alert($('a').attr("onclick"))

In XHTML onClick is not the right version.

eyazici
As IE doesn't understand XHTML (it sees it as malformed HTML) that's unlikely to be it.
NickFitz
using lowercase I get:function onclick(){alert("boo");} - so same issue
frankie boyle
+1  A: 

Internet Explorer <8 has a completely broken implementation of setAttribute and getAttribute which deal with the property with the given name instead of the attribute.

I'm not aware of a work around.

David Dorward
To expand on this: the value of the attribute whose name is 'onclick' of the anchor tag is the `alert()` call; the value of the property of the DOM node corresponding to that tag is the anonymous function.
DDaviesBrackett
+1  A: 

How can I retrieve just the javascript, and not the wrapped function, in IE 6/7

You generally don't want to rely on string values for inline event handlers at all (in fact you should generally avoid using inline event handler attributes altogether in favour of binding to functions from script — especially if you're using jQuery, where this approach is the norm). But if you have to, the workaround is the DOM method getAttributeNode.

var link= $('a')[0]; // or whatever
alert(link.getAttributeNode('onclick').value);
bobince
Totally agree strings for inline event handlers are wrong - I was just having a play and coudlnt see why IE was behaving differently... Thank you!
frankie boyle
A: 

Better than adding onclick attribute is behalf of IE6 / IE7 this solution:

$("a").click(function () { .. anything to do .. })
Jirka Kopřiva
A: 

Browser safe :

jQuery('a')[0].getAttribute('onclick');
Tanguy