Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery attr("onClick") - ie and ff

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

like image 703
frankie boyle Avatar asked Dec 02 '09 16:12

frankie boyle


2 Answers

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);
like image 91
bobince Avatar answered Oct 24 '22 05:10

bobince


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.

like image 35
Quentin Avatar answered Oct 24 '22 04:10

Quentin