How to Remove All Event Listeners from an Element in JavaScript?

Estimated read time 1 min read

To remove all event listeners from an element in JavaScript, you can use the removeEventListener method in a loop and pass it each event type that was attached to the element. To get the list of event types, you can use Object.getOwnPropertyNames(element) method to retrieve all the properties of the element, then filter out the properties that start with “on”. Here’s an example:

let element = document.getElementById("myElement");
let eventTypes = Object.getOwnPropertyNames(element)
  .filter(property => property.startsWith("on"));

eventTypes.forEach(eventType => {
  element.removeEventListener(eventType.slice(2), element[eventType]);

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply