Remove all Event Listeners from an Element using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
2 min

banner

# 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.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div id="box" style=" background-color: salmon; width: 100px; height: 100px; " > Box 1 </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

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));

remove all event listeners from element

The code for this article is available on GitHub

We added 2 click event listeners to the element.

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

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 doesn't copy event listeners added using the addEventListener() method or those assigned as properties on the element, e.g. element.onclick = function() {}.

The cloneNode method doesn't 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.

The code for this article is available on GitHub

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.