I know that Google Chrome has the function getEventListeners()
only available when the Dev Tools are open. I'm actually quite curious, Is there any functions similar to this?
If not, what other options do I have to list out all event listeners in a given element?
What I'm trying to achieve
My goal is to create a function that iterates through all the event listeners in an element and remove it.
Here is how I've been able to do it in the Chrome Dev Tools
function removeAllListeners(elementSelector){
Array.from(document.querySelectorAll(elementSelector)).forEach(element => {
const events = getEventListeners(element)
if (Object.keys(events).length !== 0) {
var clickEvents = events['click'];
for (let i = 0; i < clickEvents.length; i++) {
element.removeEventListener('click', clickEvents[i].listener);
}
}
})
}
Example Usage:
removeAllListeners('.myClassName')
Why?
I would like to be able to perform the above mentioned task in a .js
file that's loaded through using the <script src=""></script>
tag.