jQuery traversa...LOGIN

jQuery traversal - descendants

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
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("ul.level-2").children().css({"background-color":"gray","width":"200px"}); }); </script> </head> <body> <ul class="level-1"> <li class="item-i">I</li> <li class="item-ii">II <ul class="level-2">不包括自己 <li class="item-a">A</li> <li class="item-b">B <ul class="level-3"> <li class="item-1">1</li> <li class="item-2">2</li> <li class="item-3">3</li> </ul> </li> <li class="item-c">C</li> </ul> </li> <li class="item-iii">III</li> </ul> </body> </html>
submitReset Code
ChapterCourseware