Eliminating all event listeners of an element using Javascript

To handle jQuery events, you can accomplish it in a single line. For native JavaScript events, the same can be achieved. See the provided example at http://jsfiddle.net/LkfLezgd/3/. Another solution involves a function that uses the same approach as the previous one but includes an option to clone only the parent node while moving all of its children to preserve their event listeners. The function can remove event listeners on a single element or an element and all of its children. If you need to retain the object itself and are unable to use the previous function, you must wrap the function and keep track of the listener list on your own, as demonstrated in this answer.


Solution 1:

My opinion is that duplicating the node is the quickest method to complete this task, as it will eliminate all event listeners.

var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

Exercise caution since this action will eliminate the event listeners on all descendant elements of the specified node. If you intend to retain them, you will have to manually remove each listener one by one.


Solution 2:


Achieving this can be accomplished in a single line when utilizing jQuery events.

Regarding jQuery events, as indicated by

.on()

, …

$("#myEl").off()

When it comes to JavaScript events that are inherent to the language, denoted by

.addEventListener()

, there are some important considerations to keep in mind.

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/


Solution 3:


This function is built on

cloneNode

as well, however, it provides the ability to duplicate solely the root node while relocating all of its children (to maintain their event listeners).

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners
on one element:

recreateNode(document.getElementById("btn"));

Detach event listeners from an element and its descendants.

recreateNode(document.getElementById("list"), true);

If using

cloneNode

is not an option because you need to retain the object, then you can achieve your goal by wrapping the

addEventListener

function and manually monitoring the listener list, as demonstrated in this response.

Frequently Asked Questions