jQuery: the filter() method

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">



We can select all the even elements in this way:

$('li', '#test').filter('li:nth-child(even)')

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());

As you can see, this second approach is more powerful than the first.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.