jQuery Descendants
children()
and find()
are useful jQuery methods for quickly finding or getting the child or other descendants of an individual in the hierarchy by traversing down in the DOM tree, either single or multiple levels.
The children() method
The direct children of the selected element are obtained using the jQuery children()
process.
The class will be used to highlight the direct children of the <ul>
variable, which is <li>
, in the following example.
<!DOCTYPE html>
<html>
<head>
<title>Learning jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.highlight{
background: yellow;
}
</style>
<script>
$(document).ready(function(){
$("ul").children().addClass("highlight");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is just a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
Live Demo!
The find() method
The descendant elements of the selected element are obtained using the jQuery find()
process.
The find()
and children()
methods are identical, with the exception that the find()
method searches several levels down the DOM tree to find the last descendant, while the children()
method only searches a single stage. All of the <li>
elements that are descendants of the <div>
element will get a border in the following example.
<!DOCTYPE html>
<html>
<head>
<title>Learning jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script>
$(document).ready(function(){
$("div").find("li").addClass("frame");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is just a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
Live Demo!
The universal selector, on the other hand, can be used to get all descendant elements.
<!DOCTYPE html>
<html>
<head>
<title>Learning jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script>
$(document).ready(function(){
$("div").find("*").addClass("frame");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is just a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
Live Demo!