Open In App

jQuery | Traversing Descendants

Last Updated : 28 Mar, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Using jQuery we can traverse down the DOM tree in search of descendants of an element.
A descendant is a child, grandchild, great-grandchild and so on.

Traversing Down the DOM Tree: jQuery methods for traversing down the DOM tree are.

  • children()
  • find()
  • jQuery children() Method
    The children() method returns all direct children of selected element.
    This method traverses only a single level down to DOM tree.
    Example:




    <!DOCTYPE html>
    <html>
      
    <head>
        <style>
            .descendants * {
                display: block;
                border: 2px solid lightgrey;
                color: lightgrey;
                padding: 5px;
                margin: 15px;
            }
        </style>
        <script src=
      </script>
        <script>
            $(document).ready(function() {
                $("div").children().css({
                    "color": "green",
                    "border": "2px solid blue"
                });
            });
        </script>
    </head>
      
    <body>
      
        <div class="descendants" 
             style="width:500px;">
          current element
            <p>child
                <span>
                  grandchild
              </span>
            </p>
        </div>
    </body>
      
    </html>

    
    

    Output:

  • jQuery find() Method:
    jQuery find() method returns descendant elements of the selected element and all the way down to last descendant.
    Example-2:




    <!DOCTYPE html>
    <html>
      
    <head>
        <style>
            .descendants * {
                display: block;
                border: 2px solid lightgrey;
                color: lightgrey;
                padding: 5px;
                margin: 15px;
            }
        </style>
        <script src=
      </script>
        <script>
            $(document).ready(function() {
                $("div").find("span").css({
                    "color": "green",
                    "border": "2px solid blue"
                });
            });
        </script>
    </head>
      
    <body>
      
        <div class="descendants" 
             style="width:500px;">
          current element
            <p>child
                <span>grandchild</span>
            </p>
        </div>
      
    </body>
      
    </html>

    
    

    Output:



  • Like Article
    Suggest improvement
    Previous
    Next
    Share your thoughts in the comments

    Similar Reads