weenoid
weenoid

Reputation: 1186

Does jQuery continue filtering if it finds 0 matches?

I have a question regarding efficiency of jQuery filtering. I've just written quite a lengthy expression and I was wondering if jQuery stops 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 filter() call the number of matches is 0 will jQuery continue to search the DOM or will it forego the additional calls and just return 0?

Upvotes: 6

Views: 374

Answers (3)

Mr.H
Mr.H

Reputation: 61

Filtering in jQuery will return a jQuery object with DOM list of matched elements, the subsequent filter will be called on those DOM elements, and so on.

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

It is like narrowing the filter scope.

Upvotes: 0

karim79
karim79

Reputation: 342655

The nice thing about chainable calls with jQuery is that when there are no matches, nothing bad will happen.

When you call .filter and zero matches have been yielded, you are executing the subsequently chained method calls by definition because they are invoked directly on the returned object (that's what chaining is).

When there are no matches, JavaScript will still invoke each subsequently chained method on each returned object. How much wasted processing happens depends on how the specific method has been 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.

I would expect that most jQuery methods are coded such that nothing drastic happens before the length of the collection has been tested, but you never know.

Upvotes: 1

Sahil Muthoo
Sahil Muthoo

Reputation: 12496

Filtering on something that doesn't exist is going to return an empty wrapped set. Subsequent filters will be called but won't have any effect.

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

Running this on the question page returns 25.

Upvotes: 3

Related Questions