Traverse down the DOM
children()
find()
children() method
The children() method returns all direct children of the selected element (only children).
The parameters are optional. Adding parameters means filtering through the selector and filtering the elements.
<!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("p.1").css({"color":"blue","border":"5px solid green"}); }); </script> </head> <body> <div class="descendants" style="width:300px;"> <p class="1">p (儿子元素) <span>span (孙子元素)</span> </p> <p class="2">p (儿子元素) <span>span (孙子元素)</span> </p> </div> </body> </html>
Returns all <p> elements with class name "1" that are direct children of <div>
find( ) Method
find() method returns the descendant elements of the selected element, all the way down to the last descendant.
The parameter is required and can be a selector, jQuery object or element to filter elements.
<!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":"3px solid blue"}); }); </script> </head> <body> <div class="descendants" style="width:300px;"> <p>p (儿子元素) <span>span (孙子元素)</span> </p> <p>p (儿子元素) <span>span (孙子元素)</span> </p> </div> </body> </html>
Returns all <span> elements that are descendants of <div>.
Next Section