Episode 7 of 24
Traversing the DOM with jQuery
Learn to navigate parent, child, and sibling elements using jQuery traversal methods.
jQuery provides powerful methods to navigate up, down, and sideways through the DOM tree.
Going Up (Parents)
$("span").parent(); // Direct parent
$("span").parents(); // All ancestors
$("span").parents("div"); // All ancestor divs
$("span").parentsUntil("body"); // Ancestors up to (not including) body
$("span").closest(".card"); // Nearest ancestor with class "card"
Going Down (Children)
$("ul").children(); // Direct children only
$("ul").children(".active"); // Direct children with class "active"
$("div").find("p"); // All descendant paragraphs
$("div").find("*"); // All descendants
Going Sideways (Siblings)
$(".active").next(); // Next sibling
$(".active").prev(); // Previous sibling
$(".active").nextAll(); // All following siblings
$(".active").prevAll(); // All preceding siblings
$(".active").siblings(); // All siblings (not the element itself)
$(".active").nextUntil(".end"); // Siblings until ".end"
Practical Examples
// Highlight the parent of clicked element
$("li").click(function() {
$(this).parent().css("border", "2px solid blue");
});
// Toggle sibling content
$(".accordion-header").click(function() {
$(this).next(".accordion-body").slideToggle();
$(this).siblings(".accordion-header").next(".accordion-body").slideUp();
});
// Find all links inside a specific section
let links = $(".content-area").find("a");
console.log("Found", links.length, "links");
.each() — Loop Through Elements
$("li").each(function(index) {
console.log(index + ": " + $(this).text());
});