Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

jQuery

Learn step by step



jQuery Traversing-Descendants

Descendant: Descendant is a child, grandchild and so on.

From jQuery you can traverse down the DOM tree to find descendants of an element.

Traversing Down the DOM Tree

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

  • children()
  • find()
jQuery children() Method

Function children() returns all the direct children of the selected element.

This function only traverse a single level down the DOM tree.

The below given example returns all elements that are direct children of each <div> elements:


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

Output

jQuery find() Method

Function find() returns descendant elements of the selected element, all the way down to the last descendant.

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


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

Output



Related Videos