Traversing Down the DOM Tree
When working with the DOM, you’ll often need to move downward from a selected element to access its children or nested elements. jQuery provides two key methods for this:
- children() – Selects only the direct child elements.
- find() – Selects all descendant elements at any depth.
jQuery children() Method
The children() method returns all direct children of the selected element. It moves just one level down in the DOM hierarchy and ignores deeper nested descendants.
Example: Get Direct Children
The following example selects all elements that are immediate children of each <div>:
$(document).ready(function(){
$("div").children();
});
Example: Filter Children by Selector
You can also pass a selector to children() to filter the results.
The example below returns only <p> elements with the class "first" that are direct children of a <div>:
$(document).ready(function(){
$("div").children("p.first");
});
This method is perfect for targeting specific child elements without affecting deeper nested content.
jQuery find() Method
The find() method is used to search for all descendant elements of a selected element, no matter how deeply nested they are in the DOM tree.
Unlike children(), which only returns direct children, find() searches through all levels of descendants.
Example: Find Specific Descendants
The following code selects all <span> elements that are descendants of any <div>:
$(document).ready(function(){
$("div").find("span");
});
Example: Find All Descendants
You can also use the universal selector (*) to return all descendant elements of a <div>:
$(document).ready(function(){
$("div").find("*");
});
This method is especially useful when you need to apply actions or styles to deeply nested elements within a container.