How do you override inline onclick event?
JavascriptHtmlJavascript 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.