Use jQuery Filter method to select elements based on certain criteria. Example – with .filter() method you can select all p elements in your page that has a certain class.
The below .filter() method returns all p elements with class as blackColor.
$("p").filter(".blackColor ");
$(selector).filter(selection,function(index))
Parameter | Description |
---|---|
selection | Required. Selection is the criteria to filter one or more elements. To specify multiple criteria, use comma. |
function(index) | Optional. It returns for every element based on the selection criteria. If true, the element is kept otherwise the element is removed. index – The index position of the element in the set |
ActionContext | It provides the context data. |
These are the following p elements present on the page.
<p class="testClass">Paragraph with "testClass"</p>
<p class="testClass">Paragraph with "testClass"</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p class="testClass">Paragraph with "testClass"</p>
To filter out all those p that has CSS Class as testClass. I will use the .filter() method like this.
$("p").filter(".testClass").css("color", "Red");
The will turn their color to Red.
There are 2 filter conditions:
My page HTML is:
<p class="testClass">Paragraph with "testClass"</p>
<p id="test">Paragraph with id "test"</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
I will use these 2 conditions on the .filter() method separated by comma.
So the jQuery Filter method code to select these paragraphs and turn their color Red will be.
$("p").filter(".testClass,#test").css("color", "Red");
Here the first 2 p elements will be turned Red.
I have some p elements on my page:
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
I will use a jQuery Object with .filter() method. In this jQuery object I will use jQuery jquery-nth-child method to select the 3rd paragraph.
The 3rd paragraph color is turned to Red.
$("p").filter($("#div3 p:nth-child(3)")).css("color", "Red");
Now I will show the use of function parameter of the filter method.
My page HTML is:
<p>A p element <span>with one span element.</span></p>
<p>A p element <span>with</span> three <span>span</span><span> elements.</span></p>
<p>A p element <span>with one span element.</span></p>
<p>A p element <span>with</span> two <span>span elements.</span></p>
<p>A p element with no span element.</p>
The jQuery filter method code to select paragraphs having 3 span elements will be:
$("#div4 p").filter(function () {
return $("span", this).length == 3;
}).css("color", "Red");
Here the 2nd paragraph will be turned Red.
Similarly, I can use jQuery Filter method to extract even or odd element.
$("p").filter(":even");
$("p").filter(":odd");
Download the source code:
DOWNLOAD