I have recently jumped into the world of jQuery. I saw the methods find()
and filter()
but can not figure out the difference between the two.
find()
returns children of the match elements for the given selector, filter()
looks at the matched elements and returns the ones that also match the given selector.
While looking for answers to the question I found a nice blog, explaining the same. Here is the link
Also you try it on jsfiddle
<html>
<head>
<style>div{ padding:8px; border:1px solid; }</style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#filterClick").click(function () {
$('div').css('background','white');
$('div').filter('#Fruits').css('background','red');
});
$("#findClick").click(function () {
$('div').css('background','white');
$('div').find('#Fruits').css('background','red');
});
});
</script>
</head>
<body>
<h1>jQuery find() vs filter() example</h1>
<div id="Fruits">
Fruits
<div id="Apple">Apple</div>
<div id="Banana">Banana</div>
</div>
<div id="Category">
Category
<div id="Fruits">Fruits</div>
<div id="Animals">Animals</div>
</div>
<br/><br/><br/>
<input type='button' value='filter(Fruits)' id='filterClick'>
<input type='button' value='find(Fruits)' id='findClick'>
</body>