Traversing Descendants
In this page:
children()
.children() returns only the elements one level directly beneath the selected element, skipping anything nested further down. It's the descendant equivalent of parent() -- one step only, no deeper.
Example: children()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"><p>Direct</p><div><p>Nested</p></div></div>
<script>
console.log($("#box").children().length);
</script>
</body>
</html>
find()
find() searches all descendants at any depth, not just the immediate children, making it the right tool when a matching element could be nested several levels down. It behaves like running a normal selector, but scoped to inside the elements you've already selected.
Example: find()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"><p>Direct</p><div><p>Nested</p></div></div>
<script>
console.log($("#box").find("p").length);
</script>
</body>
</html>
contents()
contents() includes child nodes such as text nodes and comments, not just element nodes, which children() and find() both skip. This makes it useful when you specifically need to inspect or manipulate raw text content inside an element.
Example: contents()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Some text<p>Paragraph</p></div>
<script>
console.log($("#box").contents().length);
</script>
</body>
</html>
children and find Together
Use children() when you only care about direct child elements, and find() when a match could be nested deeper inside the structure. Combining both in one traversal chain lets you narrow a search precisely to the depth you actually need.
Example: children and find Together
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<form id="myForm"><div><label>Name</label></div></form>
<script>
console.log($("#myForm").children("div").find("label").text());
</script>
</body>
</html>
Descendant Practice
Descendant traversal is useful for working with grouped content, such as finding every label inside a specific form section without accidentally matching labels elsewhere on the page. Scoping the search to a known container avoids selectors that are too broad.
Example: Descendant Practice
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="section"><label>Email</label></div>
<script>
console.log($("#section").find("label").length);
</script>
</body>
</html>
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: