Caveat: Uses browser specific getEventListeners
, which is available in Chrome and Edge.
If you need to remove all event listeners:
// selector is optional - defaults to all elements including window and document
// Do not pass window / document objects. Instead use pseudoselectors: 'window' or 'document'
// eTypeArray is optional - defaults to clearing all event types
function removeAllEventListeners(selector = '*', eTypeArray = ['*']) {
switch (selector.toLowerCase()) {
case 'window':
removeListenersFromElem(window);
break;
case 'document':
removeListenersFromElem(document);
break;
case '*':
removeListenersFromElem(window);
removeListenersFromElem(document);
default:
document.querySelectorAll(selector).forEach(removeListenersFromElem);
}
function removeListenersFromElem(elem) {
let eListeners = getEventListeners(elem);
let eTypes = Object.keys(eListeners);
for (let eType of inBoth(eTypes, eTypeArray)) {
eListeners[eType].forEach((eListener)=>{
let options = {};
inBoth(Object.keys(eListener), ['capture', 'once', 'passive', 'signal'])
.forEach((key)=>{ options[key] = eListener[key] });
elem.removeEventListener(eType, eListener.listener, eListener.useCapture);
elem.removeEventListener(eType, eListener.listener, options);
});
}
}
function inBoth(arrA, arrB) {
setB = new Set(arrB);
if (setB.has('*')) {
return arrA;
} else {
return arrA.filter(a => setB.has(a));
}
}
}
Use:
removeAllEventListeners('a.fancyLink'); // remove all event types
removeAllEventListeners('a.fancyLink', ['click', 'hover']); // remove these types
removeAllEventListeners('*', ['click', 'hover']); // remove these types everywhere
removeAllEventListeners(); // remove everything you can
Note, this may not always work. Per MDN:
It's worth noting that some browser releases have been inconsistent on this, and unless you have specific reasons otherwise, it's probably wise to use the same values used for the call to addEventListener()
when calling removeEventListener()
.
My use of options
tries to deal with this issue by hopefully calling removeEventListener
with the same values used when the listener was added.