Last updated: Mar 5, 2024
Reading time·2 min
To remove all event listeners from an element:
cloneNode()
method to clone the element.cloneNode()
method copies the node's attributes and their values but
doesn't copy the event listeners.Here is the HTML for the examples.
<!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>
And here is the related JavaScript code.
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.
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.
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() {}
.
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.
You can learn more about the related topics by checking out the following tutorials: