The filter method
The filter method keeps only those elements in the set that match a certain selector.
Syntax
Filtering by selector:
.filter(selector);
The parameter can also be DOM elements or a jQuery object:
.filter(DOM jQuery element or object);
You can also filter elements using a function that is called separately for each of the selected elements. If it returns true, then the current element will be included in the final result, if false, then it will not be included. The elements themselves are available in the function, in the variable this, and their ordinal numbers in the set — in the variable index:
.filter(function(index, elem))
Example
Let's find all paragraphs, prepend them with the text '!' using prepend, then get only the paragraphs with the class www from the found ones using filter and prepend them with the text '?' using append:
<p>text</p>
<p>text</p>
<p class="www">text</p>
<p class="www">text</p>
$('p').prepend('!').filter('.www').append('?');
HTML the code will look like this:
<p>!text</p>
<p>!text</p>
<p class="www">!text?</p>
<p class="www">!text?</p>
Example
Let's use the function to find all paragraphs that have the tag strong and assign them the text '!!!':
<p><strong>text</strong></p>
<p><strong>text</strong></p>
<p>text</p>
<p>text</p>
$('p').filter(function() {
return $('strong', this).length === 1;
}).html('!!!');
HTML the code will look like this:
<p>!!!</p>
<p>!!!</p>
<p>text</p>
<p>text</p>