How to remove all listeners in an element
I have a button, and I added some eventlistners to it:
document.getElementById("btn").addEventListener("click", funcA, false);
document.getElementById("btn").addEventListener("click", funcB, false);
document.getElementById("btn").addEventListener("click", funcC, false);
document.getElementById("btn").addEventListener("blur" , funcD, false);
document.getElementById("btn").addEventListener("focus", funcE, false);
<button id="btn">button</button>
I can remove them by:
document.getElementById("btn").removeEventListener("click",funcA);
What if I want I want to remove all listeners at once, or I don't have the function reference (funcA)? Is there a way of doing that, or I have to remove them one by one?
I think that the fastest way to solve javascript remove all event listeners is to just clone the node, which will remove all event listeners:
var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element[removed].replaceChild(new_element, old_element);
Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time. Hope it helps!! Thank you!!