jQueryintermediate 8 min
Move around the DOM tree with parent, children, find, siblings and closest, and chain commands.
How to start from one element and reach its parent, children, siblings and descendants, and how to chain several commands in one line.
Often you know one element, such as the button that was clicked, and need to change something related to it, such as its row or its neighbour. Traversal lets you navigate from where you are instead of giving everything an id.
Traversing means moving through the DOM tree relative to an element:
.parent() and .parents(): the element above, or all ancestors..closest(selector): the nearest ancestor (or itself) that matches..children(): direct children. .find(selector): any descendant that matches..siblings(), .next(), .prev(): elements at the same level..first(), .last(), .eq(n), .filter(), .not(): narrow the current selection.Chaining: most jQuery methods return the selection, so you can keep calling methods on it:
.end() steps back to the previous selection in a chain.
$(this) is the button that was clicked..closest(".row") walks up to the task row that contains the button, and .addClass("done") strikes it through..next() selects the row after it, which we highlight as the next task..not(".done") removes finished rows from the selection, so we can count the rest.1 done, 2 to go. Each extra click updates it.Click the Done buttons in the preview, and then change .next() to .prev() and see which row is highlighted.
.parent() when you need .closest(). .parent() goes up exactly one level..children() when the element is deeper. Use .find() for any depth..parent(), .closest(), .children(), .find(), .siblings(), .next() and .prev()..first(), .eq(), .filter() and .not().Next: working with forms.
$("li").first().addClass("top").next().addClass("second");<style>
.row { padding: 6px; border: 1px solid #ccc; margin: 4px 0; }
.done { background: #d1fae5; text-decoration: line-through; }
.hl { background: #fde68a; }
</style>
<div class="row"><span>Buy milk</span> <button class="check">Done</button></div>
<div class="row"><span>Call Ravi</span> <button class="check">Done</button></div>
<div class="row"><span>Study</span> <button class="check">Done</button></div>
<p id="info"></p>
<script>
$(".check").on("click", function () {
$(this).closest(".row").addClass("done");
$(this).closest(".row").next().addClass("hl");
$("#info").text($(".done").length + " done, " + $(".row").not(".done").length + " to go");
});
</script>