views:

47

answers:

2

I have some HTML with an onclick attribute. I want to override that attribute using jQuery. Is there any way to remove the click handler using jQuery? Using unbind doesn't work.

+3  A: 

Try the .removeAttr() function:

$(function() {
    $('a').removeAttr('onclick');
});

jsfiddle demo.

Once you've got rid of the onclick attribute you could attach your own click handler.

Darin Dimitrov
Perfect! Thanks.
Skilldrick
+4  A: 
$("#theElement")[0].onclick = function() {
  whatever();
};
// -- or --
$("#theElement")[0].onclick = null;

It's not that jQuery would make the standard DOM functions and properties go away. ;-)

Tomalak
@Tomalak - you're right, but the nice thing about jQuery functions is that they apply to all the elements, so I can remove onclick from all matching elements without having to loo over them.
Skilldrick
@Skilldrick: Technically, `removeAttr()` is a loop, too. But I agree it's more convenient that writing the loop yourself.
Tomalak