Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between Grep and Filter in jQuery?
The grep() method finds elements in an array based on a filter function, while the filter() method returns DOM elements from a jQuery selection that match specific criteria.
jQuery grep() Function
The jQuery grep() function is used to filter elements from an array. It searches through array elements and returns a new array containing only elements that pass the test function.
Example
The following example demonstrates how to use grep() to filter array elements ?
<!DOCTYPE html>
<html>
<head>
<title>jQuery grep() function</title>
<style>
div {
color: blue;
margin: 10px 0;
}
p {
color: red;
margin: 10px 0;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<p></p>
<script>
var arr1 = [ 1, 7, 4, 8, 6, 1, 9, 5, 3, 7, 3, 8, 5, 8, 2 ];
$( "div" ).text( "Original array: " + arr1.join( ", " ) );
arr1 = jQuery.grep(arr1, function( n, i ) {
return ( n !== 5 && i > 6 );
});
$( "p" ).text( "Filtered array: " + arr1.join( ", " ) );
</script>
</body>
</html>
The output of the above code is ?
Original array: 1, 7, 4, 8, 6, 1, 9, 5, 3, 7, 3, 8, 5, 8, 2 Filtered array: 9, 3, 7, 3, 8, 8, 2
jQuery filter() Function
The jQuery filter() method returns elements from a jQuery selection that match specific criteria. It works with DOM elements, not arrays.
Example
The following example shows how to use filter() to select elements with a specific class ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").filter(".myclass").css("background-color", "blue");
});
</script>
</head>
<body>
<h1>Tutorialspoint</h1>
<p class="myclass">Free Text Tutorials</p>
<p>Free Video Tutorials</p>
<p>Connecting Tutors</p>
</body>
</html>
The output of the above code is ?
Tutorialspoint Free Text Tutorials (with blue background) Free Video Tutorials Connecting Tutors
Conclusion
The key difference is that grep() filters JavaScript arrays and returns a new array, while filter() filters jQuery DOM selections and returns matching elements.
