Find all the descendants of an element in jQuery

Filed Under: jQuery

In this post, we are going to discuss about an important jQuery traversing method to find all the descendents of an element. jQuery API provides find() method to carry out this task.

jQuery find() method

The jQuery find() method returns all the descendant elements like child, grandchild and so on. This method is used if you want to search all the elements deeper in the DOM tree. This method traverses downwards and finds all its descendants of the selected element. This method takes a mandatory filtering parameter to narrow down the search.

Here is the general syntax for using find() method:

  • selector.find(filter)

filter is the mandatory parameter passed to the find() method. filter could be any string selector expression, an element or a jQuery object.

jQuery find() example

Following example demonstrates the jQuery find() method usage.


<!doctype html>
<html>
<head>
<title>jQuery Traversing find</title>
<style>
    .highlight{
       background: yellow;
     }
 
    div{
      display: block;
      border: 3px solid black;
      color: black;
      padding: 5px;
      margin: 25px;
      width:250px;
     }
    span{
      display: block;
      border: 3px solid green;
      color: black;
      padding: 5px;
      margin: 25px;
      width:200px;
     }
</style>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</head>
<body>
<h2>jQuery find() demo</h2>
<div>div
<p> p - I am div's child</p>
<span>span <p>p - I am span's Child and div's Grand Child</p></span>
</div>
<script>
$( "div" ).find( "p" ).addClass("highlight");
</script>
</body>
</html>

In this example, you can see two p elements, one element is div element’s child and the other one is it’s grandchild. The find() method finds all the p element of the selected div element and changes the color to red. Below image shows the output produced by above HTML page.

jquery-find-example

You can use selector.find("*") to find all the descendants of the HTML document.

That’s all for now and you can find more traversing methods in the coming posts.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages