How to remove all event handlers for child elements of a parent element using JQuery
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();
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.
I also wondered if I needed to manually unbind every children of the removed element.
From jquery documentation you shouldn't:
jquery docs for remove
If we had any number of nested elements inside , they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.
Since I was curious if this was true I checked the source code:
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
as you can see:
jQuery.cleanData( getAll( node ) );
is cleaning all the events of all the childrens of the removed element.
So in the end: if you use $(element).remove()
or .empty()
, you are already memory leak safe!