In a script I’m writing, I’ve noticed there are two currently working ways to ‘unbind’ an event from an element.
$("elementName").each( function() { $(this).unbind('click'); });
And This way…
$("elementName").unbind('click'); });
I know .each loops through the elements but the second scripts appears to work just as well. So what am I missing, why use .each?
There’s no reason to use
.eachin this case. Most jQuery functions are intended to work on groups of matched elements so$("elementName").unbind('click')is best way to applyunbindto multiple elements at once; however, if you like typing you could use the.eachiterator and do them one a time.Generally you’ll use
.eachwhen you want to do something different to some or all of the matched elements. For example:would add a different class to each
<a>and would be an appropriate use of.each. Or anunbindexample: