jQuery Traversal - filter() Method
Example
Change the color of all div elements and then add a border to the class named "middle":
$("div").css("background", "#c8ebcc") .filter(".middle") .css("border-color", "red");
Definition and Usage
The filter() method reduces the set of matched elements to elements that match the specified selector.
Syntax
.filter(selector)
Parameter | Description |
---|---|
selector | A string value containing a selector expression to match the current element collection. |
Description
If a jQuery object representing a collection of DOM elements is given, the .filter() method will construct a new jQuery object consisting of a subset of matching elements. The selector used will test each element; all elements that match the selector will be included in the result.
Please consider the following page with a simple list:
<ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul>
We can apply this method to the set of list items:
$('li').filter(':even').css('background-color', 'red');
The result of this call is to set the background color of items 1, 3, and 5 to red, because they all match the selector (recall that :even and :odd both use a 0-based index).
Using a filter function
The second form of this method is to filter elements by function rather than by selector. For each element, if the function returns true, the element will be included in the filtered set; otherwise, it will be excluded.
Please see the following slightly complex HTML snippet:
<ul> <li><strong>list</strong> item 1 - one strong tag</li> <li><strong>list</strong> item <strong>2</strong> - two <span>strong tags</span></li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul>
We can select these list items and then filter them based on their content:
$('li').filter(function(index) { return $('strong', this).length == 1; ).css('background-color', 'red');