Filter and Find method in Jquery Traversing (Part 14)


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.

filter

<!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.

find

<!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.

Advertisements
Posted in Jquery. 1 Comment »

One Response to “Filter and Find method in Jquery Traversing (Part 14)”

  1. Learn Jquery with in 15 hrs | Chandradev's Blog Says:

    […] 14. Filter and Find method in Jquery Traversing (Part 14 […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: