Remove all Event Listeners from an Element using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove all Event Listeners from an Element using JavaScript #

To remove all event listeners from an element:

  1. Use the cloneNode() method to clone the element.
  2. Replace the original element with the clone.
  3. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="background-color: salmon; width: 100px; height: 100px"> Box 1 </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // 👇️ add 2 event listeners box.addEventListener('click', function handleClick() { console.log('box clicked first'); }); box.addEventListener('click', function handleClick() { console.log('box clicked second'); }); // ✅ Remove event listeners from Element box.replaceWith(box.cloneNode(true));

We added 2 click event listeners to the element.

Every time the element is clicked, a function is invoked for each event listeners.

To remove all event listeners from the selected element, we cloned the node using the Node.cloneNode() method and passed the result to the Element.replaceWith() method.

The only parameter the cloneNode() method takes is a boolean value. If true, the node and its children get cloned. If set to false, only the node gets cloned.

The cloneNode method copies all of the node's attributes and their values, but does not copy event listeners added using the addEventListener() method or those assigned as properties on the element, e.g. element.onclick = function() {}.

The cloneNode method does copy inline listeners. Instead of using inline listeners, use the addEventListener method.

The replaceWith method takes one or more nodes and replaces the element with the provided nodes.

We effectively create a copy of the element without any event listeners and replace the original element with the clone.

Note that this approach also removes any event listeners from the element's children.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.