From jQuery JavaScript Library
« Back to Traversing
filter( expr )
Removes all elements from the set of matched elements that do not match the specified expression(s).
This method is used to narrow down the results of a search.
Provide a comma-separated list of expressions to apply multiple filters at once.
Arguments:| expr | Expression | |
|---|
| An expression to pass into the filter |
Examples:| Name | Type |
Change the color of all divs then put a border around only some of them.
$("div").css("background", "#c8ebcc")
.filter(".middle")
.css("border-color", "red");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("div").css("background", "#c8ebcc")
.filter(".middle")
.css("border-color", "red");
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left;
border:2px white solid;}
</style>
</head>
<body>
<div></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div></div>
</body>
</html>
Selects all paragraphs and removes those without a class "selected".
$("p").filter(".selected")
Selects all paragraphs and removes those that aren't of class "selected" or the first one.
$("p").filter(".selected, :first")
filter( fn )
Removes all elements from the set of matched elements that does not match the specified function.
The function is called with a context equal to the current element (just like
$.each). If the function returns false, then the element is removed - anything else and the element is kept.
Arguments:| fn | Function | |
|---|
A function to pass into the filter
function callback(indexInJQueryObject) {
var keepItBoolean = true;
this; // dom element
return keepItBoolean;
}
|
Examples:| Name | Type |
Change the color of all divs then put a border two specific ones.
$("div").css("background", "#b4b0da")
.filter(function (index) {
return index == 1 || $(this).attr("id") == "fourth";
})
.css("border", "3px double red");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("div").css("background", "#b4b0da")
.filter(function (index) {
return index == 1 || $(this).attr("id") == "fourth";
})
.css("border", "3px double red");
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left;
border:3px white solid; }
</style>
</head>
<body>
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
<div id="fifth"></div>
<div id="sixth"></div>
</body>
</html>
Remove all elements that have a descendant ol element
$("p").filter(function(index) {
return $("ol", this).length == 0;
});