Search code examples
jqueryjquery-filter

Why use jQuery filter?


Why is there a filter function in jQuery when you can get and show / hide the elements by class?

$('.yourClass');

Solution

  • Just because you have some elements that you'd like to work with doesn't mean that they're in the DOM. Consider this contrived example:

    var $els = $('<div class="a"></div><div class="b"></div>');
    console.log($('.a'));
    console.log($els.find('.a'));
    console.log($els.filter('.a'));​
    

    Demo: http://jsfiddle.net/ambiguous/h3GMB/

    The first one, $('.a'), gives you nothing because $els aren't in the DOM yet. The second one also gives you nothing because find searches descendents. Only the third one will give you what you're looking for because filter reduces:

    the set of matched elements to those that match the selector [...]

    This sort of manipulation of things not in the DOM is fairly common when preparing template chunks for the DOM. The difference between filter and find is also fairly important even when the elements in question are in the DOM.