Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery continue filtering if it finds 0 matches?

Tags:

jquery

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?

like image 835
weenoid Avatar asked Aug 22 '11 10:08

weenoid


People also ask

How does jquery filter work?

The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. This method is often used to narrow down the search for an element in a group of selected elements.

What's the difference between filter and find?

The find() method is used to find all the descendant elements of the selected element. It finds the element in the DOM tree by traversing through the root to leaf. The filter() method is used to filters all the elements and returns the element that matches and the element that do not match are removed.


2 Answers

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.

like image 127
Sahil Muthoo Avatar answered Oct 19 '22 23:10

Sahil Muthoo


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.

like image 35
karim79 Avatar answered Oct 19 '22 23:10

karim79