Moving down the DOM tree means finding elements that are nested inside a specific container. Whether you want to target immediate children or a specific element hidden deep within thousands of tags, jQuery's descendant methods make it simple.
To move downward in the structure, there are two primary methods you need to master:
| Method | Description |
|---|---|
children() |
Returns the direct children (one level down). |
find() |
Returns all descendants down to the last child. |
The children() method only looks at the elements immediately inside the
target. It does not search for nested elements further down the tree.
// Only targets <li> that are direct children of <ul>
$("ul").children().css("border", "2px solid blue");
// You can also filter which children you want
$("div").children("p.important");
The find() method is more powerful. it searches through all levels of
nesting to find the selector you specify. To find **every** descendant, you can use the
"*" selector.
// Finds all <span> elements ANYWHERE inside the <div>
$("div").find("span").css("color", "red");
// Finds every descendant element
$("div").find("*");
A common use for find() is showing/hiding icons or labels within a specific
menu item when it is hovered.
$(".nav-item").hover(function() {
// Find the icon deep inside the clicked item and show it
$(this).find(".hover-icon").fadeIn();
}, function() {
$(this).find(".hover-icon").fadeOut();
});
find() method is significantly faster
than selecting globally. Instead of $(".child"), use
$("#container").find(".child") if you know where the element is located.