The jQuery filter()
method is a DOM utility used to select only certain elements within a jQuery wrapped set. This method accepts either a selector or a callback function to select only the elements that meet a given condition. For example, given the following markup:
<ul id="test"> <li>A</li> <li>1</li> <li>B</li> <li>2</li> </ul>
We can select all the even elements in this way:
$('li', '#test').filter('li:nth-child(even)') .addClass('test');
Even more useful is the ability of this method to accept a callback function. Let's say that we want to select only the elements whose text content is a digit:
$('li', '#test').filter(function() { return /^\d+$/.test($(this).text()); }).addClass('test');
As you can see, this second approach is more powerful than the first.