This is one of the very important question in interview. I have got this question each and every interview. So i decided to write one small article on this question.
Filter(Selector):
This method is used to search the element in entire DOM element.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <style> .bckColor { background-color: silver; } </style> <script> $(function () { $("div").filter(".bckColor").css("background-color", "green"); }); </script> </head> <body> <fieldset> <legend>Sample code for filter in Jquery </legend> <div class="bckColor"> Parent Div <div class="bckColor"> Child Div <p> This is the paragraph </p> </div> </div> </fieldset> </body> </html>
In the above example we saw that background of div element is being changed on basis of filter(selector). Filter(Selector) method is searching the element in entire DOM element.
Find(Selector):
Find method is used to search the element in only child DOM element.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <style> .bckColor { background-color:silver; } </style> <script> $(function () { $("div").find(".bckColor").css("background-color", "green"); }); </script> </head> <body> <fieldset> <legend> Sample code for find in Jquery </legend> <div class="bckColor"> Parent Div <div class="bckColor"> Child Div <p> This is the paragraph </p> </div> </div> </fieldset> </body> </html>
In the above example we saw that find(selector) is searching the element in only child DOM element.
Summary:
In the both example we saw that filter is used for searching the element in entire DOM element while Find method is used for searching element on child DOM element.
One thought on “Filter and Find method in Jquery Traversing (Part 14)”