Does jQuery continue to filter if it finds 0 matches?

I have a question regarding jQuery filtering efficiency. I just wrote a rather long expression, and I was wondering if jQuery would stop filtering if the current number of matches is 0.

passengers.filter('input.FromDate[value="01/09/2011"]') .closest('tr') .filter('input.ToDate[value="08/09/2011"]') .length; 

If after the first call to filter() number of matches is 0, will jQuery continue searching in the DOM or refuse additional calls and just return 0?

+6
source share
3 answers

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.

+1
source

Filtering out what does not exist will return an empty wrapped set. Subsequent filters will be called, but will not have any effect.

 $('div').filter('.isnt-here').end().filter('.spacer').length; 

Running this on the question page returns 25 .

+3
source

Filtering in jQuery will return a jQuery object with a DOM list of matched elements, a subsequent filter will be called on these DOM elements, etc.

If there are no matches, filtering in jQuery will return a jQuery object with an empty DOM list and will call the subsequent filter for the empty list, so it will not return a match either.

This is similar to narrowing the filter area.

0
source

Source: https://habr.com/ru/post/895578/


All Articles