How to Clear/Remove JavaScript Event Handler?

Given the following HTML fragment:

<form id="aspnetForm" onsubmit="alert('On Submit Run!'); return true;">

I need to remove/clear the handler for the onsubmit event and register my own using jQuery or any other flavor of JavaScript usage.



To do this without any libraries:

document.getElementById("aspnetForm").onsubmit = null;

With jQuery


And then proceed to add your own.


Try this, this is working for me:

$('#aspnetForm').removeAttr('onsubmit').submit(function() {   
    alert("My new submit function justexecuted!"); 

See this for more details.


For jQuery, off() removes all event handlers added by jQuery from it.


Calling .off() with no arguments removes all handlers attached to the elements.


For jQuery, if you are binding event handlers with .live, you can use .die to unbind all instances that were bound with .live.


This is an ancient question now, but given that the major browsers have all abandoned EventTarget.getEventListeners(), here's a way to remove ALL event handlers on the element and its children and retain only the HTML structure. We simply clone the element and replace it:

let e = document.querySelector('selector');
let clone = e.cloneNode(true);

This is just as much of a hack as preempting the addEventListener() prototype with a method that keeps track of every handler function, but at least this can be used after the DOM is already wired up with another script's events.

This also works about the same as above using jQuery's clone() instead of cloneNode():

let original = $('#my-div');
let clone = original.clone();

This pattern will effectively leave no event handlers on the element or its child nodes unless they were defined with an "on" attribute like onclick="foo()".


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.