jQuery Traversing Descendants


To traverse and find descendants of an element, jQuery has the following methods: children() and find().

children() method

The childreb() method in jQuery is used to return the direct children of the selected element (only a single level of direct children). Let us see an example−

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   width:600px;
}
.demo * {
   display: block;
   border: 2px solid orange;
   color: blue;
   padding: 10px;
   margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("div").children().css({"color": "gray", "border": "3px dashed blue"});
   });
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>

Output

This will produce the following output−

find() method

The find() method is used to return the descendant elements of the selected element (down to the last descendant). Let us see an example−

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   width:600px;
}
.demo * {
   display: block;
   border: 2px solid orange;
   color: blue;
   padding: 10px;
   margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("div").find("span").css({"color": "gray", "border": "3px dashed blue"});
   });
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>

Output

This will produce the following example−

Updated on: 30-Dec-2019

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements