Difference between find and filter

后端 未结 8 813
花落未央
花落未央 2020-12-09 09:19

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.

相关标签:
8条回答
  • 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.

    0 讨论(0)
  • 2020-12-09 10:05

    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>
    

    0 讨论(0)
提交回复
热议问题