Here's a function that is also based on cloneNode
, but with an option to clone only the parent node and move all the children (to preserve 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"));
Remove event listeners on an element and all of its children:
recreateNode(document.getElementById("list"), true);
If you need to keep the object itself and therefore can't use cloneNode
, then you have to wrap the addEventListener
function and track the listener list by yourself, like in this answer.