Why is there a filter function in jQuery when you can get and show / hide the elements by class?
$('.yourClass');
Why is there a filter function in jQuery when you can get and show / hide the elements by class?
$('.yourClass');
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.
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.
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:
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 becausefind
searches descendents. Only the third one will give you what you're looking for becausefilter
reduces:This sort of manipulation of things not in the DOM is fairly common when preparing template chunks for the DOM. The difference between
filter
andfind
is also fairly important even when the elements in question are in the DOM.