Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to remove all events attached to an element and its children

Tags:

jquery

I need to be able to remove events attached to an element and all its children even when I don't know what these events are. All the events are attached using jquery.

like image 669
SystemicPlural Avatar asked Nov 08 '10 10:11

SystemicPlural


People also ask

How do I remove all events from an element?

You can remove all event listeners from a DOM element in Javascript by replacing the element with a deep clone of itself. elem. cloneNode(...) will not clone the event listeners of the source element.

Are event listeners removed when element is removed?

According to the jquery Documentation when using remove() method over an element, all event listeners are removed from memory. This affects the element it selft and all child nodes. If you want to keep the event listners in memory you should use .

Can I use getEventListeners?

getEventListeners(obj) is only a Google Chrome specific Command Line Tool feature. This means that you can only use this feature inside Chrome Dev Tools when manually typing into the console. You cannot use this method in your actual JavaScript source code.


2 Answers

For jQuery 1.8 and later, use

$(element).find("*").addBack().off();

addBack() adds the original list of elements from $(element) back to the internal collection of elements held by the jQuery object (those returned by find("*")). off() removes all attached event handlers, including those using delegation.

If you just want children and not all descendants, use

$(element).children().addBack().off();

See the documentation:

  • addBack()
  • off()

For jQuery 1.7 and lower, use andSelf() instead of addBack(). For jQuery 1.6 and lower, use unbind() and die() instead of off(). For example:

$(element).children().andSelf().unbind().die();
like image 54
Andy E Avatar answered Oct 08 '22 18:10

Andy E


andSelf() function is deprecated.

Use add() function:

$(element).add("*").off();
like image 25
Ahmed El Kilani Avatar answered Oct 08 '22 18:10

Ahmed El Kilani