J S J S - 6 months ago 43
Javascript Question

Remove All Event Listeners of Specific Type

I want to remove all event listeners of a specific type that were added using

addEventListener()
. All the resources I'm seeing are saying you need to do this:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown',specific_function);


But I want to be able to clear it without knowing what it is currently, like this:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown');

Answer

That is not possible without intercepting addEventListener calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the feature wasn't implemented.

The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.

Note: This will also remove listeners on element's children.

var el = document.getElementById('el-id'),
    elClone = el.cloneNode(true);

el.parentNode.replaceChild(elClone, el);