jQuery Traversing Descendants: children() and find() Functions
Understanding Descendants in jQuery Traversing
You can use jQuery to search and find the descendants of elements. For this, you need to traverse down the DOM tree.
A descendant can be a child, grandchild, great-grandchild, etc.
Traversing Down the DOM Tree
The following are two important jQuery techniques for navigating the DOM tree:
-
children()
-
find()
jQuery children() Method
The children method in jQuery is used to return the immediate children of an element. This approach traverses only one level of the DOM tree.
In the following example, all elements that are direct children of each
Example of children method in jQuery
$(document).ready(function(){
$("div").children();
});
An optional parameter to narrow down your child's search.
In this example returns all
elements that are direct children of
"first"
:Example
$(document).ready(function(){
$("div").children("p.first");
});
jQuery find() Method
The descendant elements of the selected element are returned the find()
method, all the way down to the last descendant.
Here, if a element is descendant of
Example of find method in jQuery
$(document).ready(function(){
$("div").find("span");
});
All descendants of
Example
$(document).ready(function(){
$("div").find("*");
});