The filter() method returns elements that match a certain criteria.
The filter() method is used to filter out all the elements that do not match the selected criteria and those matches will be returned.
This method is often used to narrow down the search for an element in a group of selected elements.
Syntax :-
$(selector).filter(criteria, function(index))
Parameters:
criteria : It specifies a selector expression, a jQuery object or one or more elements to be returned from a group of selected elements.
Tip: To specify multiple criteria, use comma.
function(index) : It specifies a function to run for each element in the set. If the function returns true, the element is kept. Otherwise, it is removed.
index : The index position of the element in the set.
Example :-
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>jQuery Filter</title> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> | |
<script> | |
$(document).ready(function() { | |
$('li').filter(".first, .last").css("color", "blue").css("backgroundColor", "yellow"); | |
}); | |
</script> | |
</head> | |
<body> | |
<ul> | |
<li class="first"> This is Roshan</li> | |
<li> This is Roshan Kumar </li> | |
<li class="last"> This is Roshan Jha </li> | |
</ul> | |
</body> | |
</html> |