Remove all Event Listeners from an Element using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 01 20222 min read

Remove all Event Listeners from an Element using JavaScript #

To remove all event listeners from an element, clone the element using the cloneNode() method and replace the original element with the clone - box.replaceWith(box.cloneNode(true)). 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 first 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 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee