The good thing about jQuery chaining is that when there are no matches, nothing bad will happen.
When you call .filter and get null matches, you make calls, followed by a method call by definition, because they are called directly on the returned object (what is a chain).
If there are no matches, JavaScript will still call each subsequent method in each returned object. How much processing will be wasted depends on how the particular method was implemented.
$.fn.doesItTryToDoStuff = function() { alert('called'); // here I could have some wasteful process // which could foolishly be executed // even when there are no elements return this.each(function() { $(this).css("border", "1px solid red"); }); }; $("input").filter("[value='foo']").doesItTryToDoStuff().doesItTryToDoStuff();
Demo version
I would expect most jQuery methods to be encoded in such a way that nothing will happen before the length of the collection is verified, but you never know.
source share