How do you override inline onclick event?

JavascriptHtml

Javascript Problem Overview


This seems deceptively simple.

How do you override the onclick event in the following HTML using JavaScript?

<a id="sample" href="..." onclick="alert('hello world')" />...</a>

I've tried it with jQuery, but that didn't do the trick:

$('#sample').attr('onclick','alert("done")')

Assume the HTML is pre-written and cannot be changed, other than manipulating it with JavaScript.

Javascript Solutions


Solution 1 - Javascript

Try this:

// Setting the DOM element's onclick to null removes 
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });

Solution 2 - Javascript

This can also be done without jQuery:

document.getElementById("sample").setAttribute('onclick','alert("done")');

Solution 3 - Javascript

<a id="sample" href="..." onclick="alert('hello world'); return false;" />...</a>

Or

$('#sample').attr('onclick','alert("done"); return false;')

Despite being able to set the return false; either directly in the onclick or by using jQuery, it doesn't actually require jQuery to be used at all. The benefit is if for whatever reason your jQuery script leads to a 404, your code will still work.

I found the answer here.

Solution 4 - Javascript

Try:

document.getElementById("sample").onclick = $.noop;

$.noop == function(){};

jQuery noop

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDiodeus - James MacFarlaneView Question on Stackoverflow
Solution 1 - JavascriptAndrew HareView Answer on Stackoverflow
Solution 2 - JavascriptsupershneeView Answer on Stackoverflow
Solution 3 - JavascriptBen EverardView Answer on Stackoverflow
Solution 4 - JavascriptDavid MurdochView Answer on Stackoverflow