jQuery Traversal - Descendants
Descendants are children, grandchildren, great-grandchildren, etc.
With jQuery, you can traverse down the DOM tree to find the descendants of an element.
Traverse down the DOM tree
The following are two jQuery methods for traversing down the DOM tree:
children()
find()
jQuery children() method
children() method returns all direct child elements of the selected element.
This method will only traverse the DOM tree one level down.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .descendants * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("div").children().css({"color":"red","border":"2px solid red"}); }); </script> </head> <body> <div class="descendants" style="width:500px;">div (当前元素) <p>p (儿子元素) <span>span (孙子元素)</span> </p> <p>p (儿子元素) <span>span (孙子元素)</span> </p> </div> </body> </html>
jQuery find() method
The find() method returns the descendant elements of the selected element, all the way down to the last descendant.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .descendants * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("div").find("span").css({"color":"red","border":"2px solid red"}); }); </script> </head> <body> <div class="descendants" style="width:500px;">div (当前元素) <p>p (儿子元素) <span>span (孙子元素)</span> </p> <p>p (儿子元素) <span>span (孙子元素)</span> </p> </div> </body> </html>