Categories
JavaScript Answers

How to remove all event listeners of a DOM object with JavaScript?

Spread the love

Sometimes, we want to remove all event listeners of a DOM object with JavaScript.

In this article, we’ll look at how to remove all event listeners of a DOM object with JavaScript.

How to remove all event listeners of a DOM object with JavaScript?

To remove all event listeners of a DOM object with JavaScript, we can get all event listener names with getEventListeners.

And then we call remove on each event listener.

For instance, we write

for (const eventType of Object.keys(getEventListeners(document))) {
  getEventListeners(document)[eventType].forEach((o) => {
    o.remove();
  });
}

to use Object.keys(getEventListeners(document)) to get an array of event listener name strings.

Then we call getEventListeners(document)[eventType].forEach with a callback that calls remove to remove each event listener.

Conclusion

To remove all event listeners of a DOM object with JavaScript, we can get all event listener names with getEventListeners.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *