jQuery Traversing Descendants

jQuery Traversing Descendants

An ancestor is a child, grandchild, great-grandchild, and so on. With jQuery you can traverse down the DOM tree to find descendants of an element.

Two useful jQuery methods for traversing down the DOM tree are:

  1. children()
  2. find()

1. jQuery Children() Method

In jQuery, The Children() is an inbuilt method in jQuery which is used to find the child element related to the selected element. The Children() method returns the direct child element of the selected element. This method only traverse a single level down the DOM tree.

Syntax

$(element).Children()

Example

The following example returns all elements that are direct children of each <li> elements:

<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * { 
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("li").children().css({ "color": "green", "border": "4px solid red" });
});
</script>
</head>
<body class="ancestors">body (great-great-grandparent)
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent) 
<li>li (direct parent)
<span>span</span>
</li>
</ul> 
</div>
</body>
</html>

Output

In the above output returns all elements that are direct children of each <li> elements. So it will show the red color box as child.

jquery Traversing Descendants

2. jQuery find() Method

In jQuery, The find() is an inbuilt method in jQuery which is used to find all the descendant elements of the selected element. It will traverse all the way down to the last leaf of the selected element in the DOM tree.

Syntax

$(element).find()

Example

Following example demonstrates the find() method usage.

<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * { 
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
 $("div").find("span").css({ "color": "green", "border": "4px solid red" });
});
</script>
</head>
<body class="ancestors">body (great-great-grandparent)
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent) 
<li>li (direct parent)
<span>span</span>
</li>
</ul> 
</div>
</body>
</html>

Output

jquery Traversing Descendants
Prev Next