Quick Reach
The $.filter method
The filter method is used to reduce or filter elements that match the selector or passed the criteria given in the filter jQuery method. For example, in your paragraphs of HTML document (<p>), you want to change the color of only those which class is short_desc.
See example of filter method
Similarly, you have multiple DIV elements in your document and you want to filter and hide only with the class name left_menu.
Syntax of jQuery filter
Following is the basic syntax of jQuery filter method:
.filter( selector/element )
For example
$(“li”).filter(“.midli”)
That means, filter li in the document with class name .midli. After filtering, perform the given action on it.
Similarly,
$(“div”).filter(“.leftmenu”)
This will traverse through the document, find all Div elements and only filter or reduce to those with class name left_menu.
Still confused? See the following example online to learn more about the filter method.
Working example of filter() method of jQuery
In the following example, as the button is clicked, the $.filter method will traverse through the document and find all <p> elements. Next, it will find the .midtext class in <p> tags and change its color to the black.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<!DOCTYPE html>
<head>
<title>The filter method</title>
<script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function() {
$(“#filterP”).click( function() {
$(“p”).filter(“.midtext”).addClass(“postFilter”);
});
});
</script>
<style>
.toptext {color:green;}
.midtext {color:red;}
.bottomtext {color:orange;}
.postFilter {color:#000000;}
</style>
</head>
<body>
<p class=“toptext”>This is filter example</p>
<p class=“midtext”>This is filter example</p>
<p class=“bottomtext”>This is filter example</p>
<input id=“filterP” type=“button” value=“Filter <p>” />
</body>
</html>
|
Opposite to the filter method is the not() method. Click here to learn how to use the not() method of jQuery.
Leave A Comment?