0

Say some DOM node (like a <a> tag) is bind with some events, like click to open a popup or anything. But I can't read the code which contains the binding stuff. How do I unbind them all? Is there any simple way/hack?

update again:

--

I checked the Elements > Event Listeners with my Chrome and found that there is a click event handler on my a, to make sure I am right, I tried the following steps:

First, I manually added a click handler from the console like this:

$a.click(function(){console.log(1)});

And I go back to the listeners tab, hit the refresh button, there is one more (now two handlers).

Then I use:

$a.off();

And I go back again, the one that I manually added is gone, remains only one handler (the one I want to git rid of)

And I used the replace-node way, and go back again, I found that the click handler is totally gone. That is what I want.

So, it's like $a.off() is not working, even though it's pretty sure that the event is bind to the element itself, not its parent nodes.

--

update:

  1. I am using jQuery
  2. I tried $.unbind() and $.off(), neither works
  3. I used $('#myEl').replaceWith($('#myEl').clone()); and this works fine. But it seems this way is not very perfect.
AGamePlayer
  • 7,404
  • 19
  • 62
  • 119

3 Answers3

2

You can create a clone of the element and replace it. Cloning an element will not clone the attached event listeners.

var original = document.getElementById('id'),
var clone = original.cloneNode(true);

original.parentNode.replaceChild(clone, original);
Danny
  • 614
  • 3
  • 11
2

There is no API to do that. Depending on which modifications have been made to the element, you could clone the node, move the children and replace the original with its clone:

var clone = element.cloneNode();
while (element.firstChild) {
  clone.appendChild(element.lastChild);
}
element.parentNode.replaceChild(clone, element);

cloneNode will copy all the attributes, but not any changes that have been made to DOM properties.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

Maybe you can use jquery .unbind():

$('a').unbind()

In new version jquery, .off() is suggest to use.

$('a').off()

if this not working, it means your event is not binding on this element but others like parent element, you may have this code in your script, and you have to decide how to deal with that:

$('.parent').on('click','a',callback);
Sing
  • 3,942
  • 3
  • 29
  • 40