How to remove all listeners in an element?

JavascriptDom EventsAddeventlistener

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

I think that the fastest way to do this 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.parentNode.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.

Solution 2 - Javascript

If you’re using jquery events, this can be done in one line:

For jQuery events (.on()):

$("#myEl").off()

For native javascript events (.addEventListener()):

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/

Solution 3 - Javascript

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);


If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

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
QuestionDerek 朕會功夫View Question on Stackoverflow
Solution 1 - JavascriptBen DView Answer on Stackoverflow
Solution 2 - JavascriptDukeView Answer on Stackoverflow
Solution 3 - JavascriptuserView Answer on Stackoverflow