39

I have a div element with several elements inside it like buttons and so forth which have event handlers attached to them. I know its possible to go:

$("#button1").off()

To remove the handler for a button but I would like to do something like this if possible:

$("#div1").removeChildHandlers();

Is there a native function in JQuery to do this or would I have to loop them all the elements and remove 1 by 1?

Nuvolari
  • 1,103
  • 5
  • 13
  • 29

4 Answers4

47

jQuery will do the looping for you for just the direct children:

$("#div1").children().off();

or if you want all descendants:

$("#div1").find("*").off();
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    Thanks I think that covered just about all possibilities I was looking for. – Nuvolari Dec 19 '12 at 03:26
  • Thanks for this. I found it's hard to determine whether an event handler already exists without manually tracking it. Turning all the descendant handlers off allows me to just re-apply them right after. Likely not good for performance, but a quick solution is great to have! – Kyle Tolle Sep 07 '13 at 20:08
  • what is the main difference between `$("#div1").children().off()` from `$("#div1").off()`? – Malcolm Salvador May 15 '17 at 05:42
  • 1
    @Malky.Kid - `$("#div1").off()` removes event handlers from only the `#div1` element itself. `$("#div1").children().off()` operates on only the children of `#div` and does not operate on `#div` at all. So, it depends upon which elements you want to operate on. – jfriend00 May 15 '17 at 05:48
  • @jfriend00 my gratitude – Malcolm Salvador May 15 '17 at 05:55
4

Does this help:

$("#div1").find('*').off();
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
1

Try with

$("#div1 >* ").off();

Or:

$("#div1").find('button').off();

if you're talking about <button> elements

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

IMHO the better practice and better performant option would be to attach the handler to the outside parent with the on method...

$("#div1").find("click", ".childButton", magicFunction);

Then to remove all listeners you can call off on just the parent element.

$("#div1").off();
cytek04
  • 472
  • 5
  • 17