Google News
logo
jQuery Traversing Descendants
A descendant is a child, grandchild, great-grandchild, and so on.  With jQuery you can traverse down the DOM tree to find descendants of an element.

Traversing Down the DOM Tree

jQuery provides the useful methods children() and find() such as that you can use to traverse down in the DOM tree either single or multiple levels to easily find or get the child or other descendants of an element in the hierarchy.

  • children()
  • find()
jQuery children() Method
The jQuery children() method get the child element of each element specified using selector expression.
<!DOCTYPE html>
<html>
<head>
<title>jQuery children() Method</title>
 
<script src="js/jquery-3.2.1.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
    $("ul").children().css({"color": "#F60", "border": "2px solid #0099da"});
});
</script>
<style type="text/css">
.children_elements * { 
    display: block;
    border: 2px solid #CCC;
    color: #000;
    padding: 5px;
    margin: 15px;
}
</style>
</head>
 
<body class="children_elements">
 
 body (great-grandparent)
  <div style="width:500px;">div (grandparent)
    <ul>ul (direct parent)  
      <li>li (child)
        <span>span (grandchild)</span>
      </li>
    </ul>   
  </div>
  
</body>
</html>
Output :
jQuery find() Method

The jQuery find() method is used to get the descendant elements of the selected element.

The find() and children() methods are similar, except that the find() method search through multiple levels down the DOM tree to the last descendant, whereas the children() method only search a single level down the DOM tree.

The following example returns all <span> elements that are descendants of <div> :

<!DOCTYPE html>
<html>
<head>
<title>jQuery find() Method</title>
<script src="js/jquery-3.2.1.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
    $("div").find("span").css({"color": "#0099da", "border": "2px solid #0099da"});
});
</script>
<style type="text/css">
.my_div_color * { border: 2px solid #999; color:#999; display:block;  padding:5px; margin:10px 5px;}
</style>
</head>
 
<body>
 
<div class="my_div_color" style="width:300px;">FTL (current element) 
  <p>Free Time Learning (child)
    <span>www.freetimelearning.com (grandchild)</span>     
  </p>
  <p>Free Time Learning (child)
    <span>www.freetimelearning.com (grandchild)</span>
  </p> 
</div>
 
</body>
</html>
Output :