jQuery .filter()
Learn all about the jQuery function .filter().
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:
1
2
3
4
5
6
7
8
|
|
We can apply this method to the set of list items:
1
|
|
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).
Using a Filter Function
The second form of this method allows us to filter elements against a function rather than a selector. For each element, if the function returns true
(or a "truthy" value), the element will be included in the filtered set; otherwise, it will be excluded. Suppose we have a somewhat more involved HTML snippet:
1
2
3
4
5
6
7
8
9
|
|
We can select the list items, then filter them based on their contents:
1
2
3
4
5
|
|
This code will alter the first list item only, as it contains exactly one <strong>
tag. Within the filter function, this
refers to each DOM element in turn. The parameter passed to the function tells us the index of that DOM element within the set matched by the jQuery object.
We can also take advantage of the index
passed through the function, which indicates the 0-based position of the element within the unfiltered set of matched elements:
1
2
3
4
5
|
|
This alteration to the code will cause the third and sixth list items to be highlighted, as it uses the modulus operator (%
) to select every item with an index
value that, when divided by 3, has a remainder of 2
.