Why use jQuery filter?

864 views Asked by At

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

$('.yourClass');
3

There are 3 answers

0
mu is too short On BEST ANSWER

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.

0
ThoKra On

As from the document:

Given a jQuery object that represents a set of DOM elements, the .filter() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result.

Consider a page with a simple list on it:

We can apply this method to the set of list items:

$('li').filter(':even').css('background-color', 'red');

The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that :even and :odd use 0-based indexing).

The filter function is used to filter the result of your original query into specific elements.

But if you are referring to .hide() and .show(), it's a choice you have, instead of splitting your code into both css and javascript, you have a couple of methods that are cross browser to do the job instead.

0
Gideon On

filter allows you to filter part of the set you have, let's say we have a list of items, and to all items I want to add a class, but to part of it I want to add another class:

$('#mylist li').addClass('someclass').filter('.someotherclass').addClass('filtered');

I could have split this up in two queries.