Remove all Event Listeners from an Element using JavaScript

In this tutorial you will learn how to remove all Event Listeners from an Element using JavaScript;

In Js to remove all event listeners from an element or dom document we can use cloneNode() method to clone the element and replace the original element. The cloneNode() method copies the node’s attributes and their values, but doesn’t copy the event listeners.

HTML Code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="element-box" style="background-color: salmon; width: 100px; height: 100px">
      Box 1
    </div>
  </body>
</html>

Js Part:

<script>
  const elementBox = document.getElementById('element-box');

  // add 2 event listeners
  elementBox.addEventListener('click', function handleClick() {
    console.log('div element clicked first');
  });

  elementBox.addEventListener('click', function handleClick() {
    console.log('div element clicked second');
  });

  // Remove event listeners from Element
  elementBox.replaceWith(elementBox.cloneNode(true));
</script>