The jQuery has following methods for traversing down the DOM tree:
jQuery children() Method
The children() method is used to get the direct children element of the selected element.
Example of Code
<style>
.jQuery-example-descendants-children * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".jQuery-example-descendants-children").children().css({"color": "red", "border": "2px solid red"});
});
</script>
<div class="jQuery-example-descendants-children" style="width:500px;">div (current element)
<p>p (child)
<span class="jQuery-descendants-children-span">span (grandchild)</span>
</p>
</div>
Output
div (current element)p (child)span (grandchild)
jQuery find() Method
The find() method is used to get the descendant elements of the selected element, all the way down to the last descendant.
Example of Code
<style>
.jQuery-descendants-find * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".jQuery-descendants-find").find(".jQuery-descendants-find-span").css({"color": "red", "border": "2px solid red"});
});
</script>
<div class="jQuery-descendants-find" style="width:500px;">div (current element)
<p>p (child)
<span class="jQuery-descendants-find-span">span (grandchild)</span>
</p>
</div>
Output
div (current element)p (child)span (grandchild)
