jQuery .filter() reduces the matched elements by selector
Syntax and Description
filter method reduces the set of matched elements by the selector or the function.
.filter(selector)
selector
: a string containing a selector expression to match elements against
.filter(function)
function: A function used as a test for each element in the set
The Return value is the new jQuery object.
Filter by attribute id
The following code selects all div
elements and
changes the background color. Then it filter div
elements
by its id value. After that it adds border for the filtered elements.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from ww w. j ava 2s . c o m-->
$("div").css("background", "blue")
.filter(function (index) {
return $(this).attr("id") == "fourth" ;
})
.css("border", "1px solid red");
});
</script>
<style>
div { border:2px white solid;}
</style>
</head>
<body>
<body>
<div id="first">java2s.com</div>
<div id="second">java2s.com</div>
<div id="third">java2s.com</div>
<div id="fourth">java2s.com</div>
<div id="fifth">java2s.com</div>
<div id="sixth">java2s.com</div>
</body>
</html>
Filter by index
The following code filters div
elements by index.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w ww. java 2s . c om-->
$("div").css("background", "blue")
.filter(function (index) {
return index == 1 ;
})
.css("border", "1px solid red");
});
</script>
<style>
div { border:2px white solid;}
</style>
</head>
<body>
<body>
<div id="first">java2s.com</div>
<div id="second">java2s.com</div>
<div id="third">java2s.com</div>
<div id="fourth">java2s.com</div>
<div id="fifth">java2s.com</div>
<div id="sixth">java2s.com</div>
</body>
</html>
Filter by css style
Filter method can remove elements with specified class name.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- www . jav a 2s . c om-->
$("div").css("background", "yellow").filter(".blue").css("border-color", "red");
});
</script>
<style>
div { border:2px white solid;}
</style>
</head>
<body>
<body>
<div class=blue>java2s.com</div>
<div>java2s.com</div>
<div>java2s.com</div>
<div>ja va2s.com</div>
<div>java2s.com</div>
<div>java2s.com</div>
</body>
</html>
Filter by node type
The following code shows how to filter by node type.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from www . j a va 2s . co m-->
$("p").contents().filter(function(){ return this.nodeType != 1; }).wrap("<b/>");
});
</script>
</head>
<body>
<body>
<p>Hello <span>span</span>data. java2s.com</p>
</body>
</html>