Suppose I have the following jQuery:
$container = $('#container');
$container.find('.foo').hide(500).remove();
There’s no point in calling anything past $container if there is no #container element on the page, so I could do this:
if ($container.length > 0) { // Is there such an element?
$container.find('.foo').hide(500).remove();
}
But is there any point to checking? If $container is an empty collection, will jQuery automatically ignore the rest of the calls?
I’ve verified that the code in an each callback is never called on empty collections, but I’m not sure how to test this for other chained methods; I don’t know whether hide() is being called or not, for instance.
Looking at the source code of $().find() it loops through this.length:
So I would say, you don’t need it, the loop never gets executed anyway.
Usually jQuery just does nothing if your selector returns an empty result set.