jQuery filter() Method |
-- Learning not just technology, but also dreams!
jQuery filter() Method
The filter() method is used to filter elements from a set of matched elements based on a specified condition. It returns a new jQuery object containing only the elements that match the given criteria.
Syntax:
$(selector).filter(function(index))
Parameters:
function(index): A function that returns true or false for each element in the selection. If it returns true, the element is included in the result.
Example 1: Filter elements by index
This example filters all <li> elements and keeps only those at even indices (0, 2, 4, ...).
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("li").filter(function(index){
return index % 2 === 0;
}).css("background-color", "yellow");
});
</script>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</body>
</html>
Example 2: Filter elements by attribute
This example filters <div> elements with a specific data-type attribute.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").filter("[data-type='important']").css("color", "red");
});
</script>
</head>
<body>
<div data-type="important">This is important</div>
<div data-type="normal">This is normal</div>
<div data-type="important">This is also important</div>
</body>
</html>
Example 3: Filter elements by text content
This example selects <p> elements that contain specific text.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").filter(function(){
return $(this).text().indexOf("Hello") !== -1;
}).css("font-weight", "bold");
});
</script>
</head>
<body>
<p>Hello, world!</p>
<p>Goodbye.</p>
<p>Hello, everyone!</p>
</body>
</html>
Summary:
filter()allows you to selectively keep elements based on a condition.- You can use functions, attributes, or text content as filtering criteria.
- It does not modify the original DOM; instead, it creates a filtered subset.
Related Tutorials
- jQuery Tutorial
- jQuery Introduction
- jQuery Installation
- jQuery Syntax
- jQuery Selectors
- jQuery Events
Further Reading
Reference Manual
- jQuery Selectors
- jQuery Event Methods
- jQuery Effect Methods
- jQuery HTML/CSS Methods
- jQuery Traversal Methods
- jQuery AJAX Methods
- jQuery Miscellaneous Methods
- jQuery Properties
YouTip