jQuery | Traversing Descendants
Using jQuery we can traverse down the DOM tree in search of descendants of an element.
A descendant is a child, grandchild, great-grandchild and so on.
Traversing Down the DOM Tree: jQuery methods for traversing down the DOM tree are.
- children()
- find()
The children() method returns all direct children of selected element.
This method traverses only a single level down to DOM tree.
Example:
<!DOCTYPE html> < html > < head > < style > .descendants * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </ style > < script src = </ script > < script > $(document).ready(function() { $("div").children().css({ "color": "green", "border": "2px solid blue" }); }); </ script > </ head > < body > < div class = "descendants" style = "width:500px;" > current element < p >child < span > grandchild </ span > </ p > </ div > </ body > </ html > |
chevron_right
filter_none
Output:
jQuery find() method returns descendant elements of the selected element and all the way down to last descendant.
Example-2:
<!DOCTYPE html> < html > < head > < style > .descendants * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </ style > < script src = </ script > < script > $(document).ready(function() { $("div").find("span").css({ "color": "green", "border": "2px solid blue" }); }); </ script > </ head > < body > < div class = "descendants" style = "width:500px;" > current element < p >child < span >grandchild</ span > </ p > </ div > </ body > </ html > |
chevron_right
filter_none
Output: