In logical relationships, a descendant is a child, grandchild, great-grandchild, and so forth.
jQuery offers useful methods like children()
and find()
. These methods help you move down the DOM tree, either by single or multiple levels, to easily locate or get the child or other descendants of an element within the hierarchy.
children()
MethodThe jQuery children()
method is used to find the direct children of a selected element.
In the example below, the direct children of the <ul>
element, which are <li>
, will be highlighted by adding the class .highlight
when the document is ready.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery children() Demo</title>
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul").children().addClass("highlight");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
find()
MethodThe jQuery find()
method is used to retrieve the descendant elements of a selected element.
The find()
and children()
methods are similar, but the find()
method searches through multiple levels down the DOM tree to the last descendant, whereas the children()
method only searches one level down the DOM tree. In the example below, a border will be added around all the <li>
elements that are descendants of the <div>
element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery find() Demo</title>
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("li").addClass("frame");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
However, if you want to get all the descendant elements, you can use the universal selector.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery find() Demo</title>
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("*").addClass("frame");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>