jQuery Traversing
Traversing means moving through the HTML family tree to reach elements that are related to the one you already have. Once you have selected an element with jQuery, you rarely stay put. You often need to jump to its parent, hop down to a child, or step sideways to a neighbour. jQuery gives you a whole set of methods for this kind of movement.
What is traversing?
Think of an HTML document as a family tree. Every element sits somewhere in that tree, with elements above it (ancestors), below it (descendants), and beside it (siblings). Traversing is the act of starting at one selected element and 'walking' to a related element based on that relationship, instead of writing a brand-new selector from scratch.
This matters because real pages change. A list item you clicked might be anywhere in the page, but relative to itself its parent list is always one step up. Traversing lets you write code that follows the relationship rather than a fixed address, so it keeps working even when the markup shifts around.
The three directions
- Upwards (ancestors) - move towards the top of the tree using methods like parent(), parents(), and parentsUntil().
- Downwards (descendants) - move towards the leaves using methods like children() and find().
- Sideways (siblings) - move across the same level using methods like siblings(), next(), and prev().
In this lesson we will focus on the idea of movement itself and see a few quick examples. The next lessons zoom in on each direction one at a time.
Move up to the direct parent
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="box">
<span>I am a span inside a div.</span>
</div>
<script>
$(document).ready(function() {
// Start at the <span>, then walk one step up to its parent
$("span").parent().css("border", "2px solid red");
});
</script>
</body>
</html>Move down to the children
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="box">
<p>First child paragraph.</p>
<span>Second child span.</span>
</div>
<script>
$(document).ready(function() {
// Start at the <div>, then walk down to its direct children
$("div.box").children().css("color", "blue");
});
</script>
</body>
</html>Move sideways to the siblings
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div>
<h2>Section Title</h2>
<p>First sibling paragraph.</p>
<p>Second sibling paragraph.</p>
</div>
<script>
$(document).ready(function() {
// Start at the <h2>, then reach every element beside it
$("h2").siblings("p").css("background", "#ffeeba");
});
</script>
</body>
</html>Exercise: jQuery Traversing
What is the difference between .find() and .children()?