Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all event handlers for child elements of a parent element using JQuery

Tags:

jquery

Given a specific parent node, for example a dynamically created modal div. After adding a bunch of dynamic html to it and then binding those elements to click, mouseover, etc events, is there a way to un-bind all of the events associated with child elements of the modal div. In my specific example, once the modal div is hidden it is then removed from the dom entirely and then recreated from scratch each time it is needed.

I am looking for a way to not have to track all of the specific bindings, but rather just use one call to say: get any children elements that have bindings and 'off' them.

Note: I can validate that removing the element from the dom and then recreating it does not kill the binding as opening and closing the modal div causes the bound events to be fired the same number of times the div was created. I am using $(document).on('click', '#abc',function(e) {}); to bind elements.

like image 256
MindWire Avatar asked Aug 17 '12 20:08

MindWire


2 Answers

You can use unbind() if you used bind() to attach the events.

  $('#foo').children().unbind();
  $('#foo').children('.class').unbind(); //You can give selector for limiting clildren

or

Use off() if you used on() to bind events.

 $('#foo').children().off();
 $('#foo').children('class').off();   //You can give selector for limiting clildren

For removing the event from all descendants instead of direct children you can use Descendant Selector (“ancestor descendant”) .

$('#foo *').off(); 
like image 62
Adil Avatar answered Sep 21 '22 13:09

Adil


Yeap - use off() with no params - that will unbind all events bound.

$('#parent *').off();

If you meant literally children, i.e. not children OR descendants, use #parent > * instead.

like image 27
Mitya Avatar answered Sep 21 '22 13:09

Mitya