Introduction
Basically, Find and Filter functions in jQuery sound very similar. In this blog, we are going to see when to use Filter instead of Find.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
-
-
-
- <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
-
- </head>
- <body>
- <h3>Filter Vs find</h3>
- <ul id="ulist">
- <li id="li1"class="li" > Apple</li>
- <li id="li2" class="li">Orange</li>
- <li id="li3"> Grapes </li>
- </ul>
-
- <h4>Output</h4>
- <ul id="message">
- </ul>
- <br/>
- <button id="btnClick">Click Me</button>
-
- </div>
- <script>
- $(document).ready(function () {
-
-
- var $name=$('#ulist li');
- var $li=$name.find(".li");
- var $output =$('#message');
- $("#btnClick").on("click",function(){
- debugger;
- if($li.length)
- {
- var html="";
- $li.each(function()
- {
- html+="<li>" + $(this).text() + "</li>";
- });
- $output.append(html)
- }
- else
- {
- $output.append("<li> No Element Found</li>")
- }
-
- })
- })
-
-
- </script>
-
- </body>
- </html>
Output
Click on the "Click Me" button.
The above HTML page consists of three items in the list. In the jQuery, we used the selector ($name=$('#ulist li')) to select the li. From the selector, we found the li which consists of the class name as li ($name.find(".li")), but no element is selected using the Find function.
Reason
The Find function will always look for the child element whereas the Filter function will check for an exact match.
filter()
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
-
-
-
- <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
-
- </head>
- <body>
- <h3>Filter Vs find</h3>
- <ul id="ulist">
- <li id="li1"class="li" > Apple</li>
- <li id="li2" class="li">Orange</li>
- <li id="li3"> Grapes </li>
- </ul>
-
- <h4>Output</h4>
- <ul id="message">
- </ul>
- <br/>
- <button id="btnClick">Click Me</button>
-
- </div>
- <script>
- $(document).ready(function () {
-
-
- var $name=$('#ulist li');
- var $li=$name.filter(".li");
- var $output =$('#message');
- $("#btnClick").on("click",function(){
- debugger;
- if($li.length)
- {
- var html="";
- $li.each(function()
- {
- html+="<li>" + $(this).text() + "</li>";
- });
- $output.append(html)
- }
- else
- {
- $output.append("<li> No Element Found</li>")
- }
-
- })
- })
-
-
- </script>
-
- </body>
- </html>
Output
Now, you can see the result with the list consisting of li class names by clicking the button.
Reason
The Filter function always looks for the exact match.
I hope you have learned from this blog. Your valuable feedback, questions, or comments about this blog are always welcome.