牛骨文教育服务平台(让学习变的简单)

jQuery 遍历 - 后代


jQuery 遍历 - 后代


后代是子、孙、曾孙等等。

通过 jQuery,您能够向下遍历 DOM 树,以查找元素的后代。


下遍历 DOM 树

下面是两个用于向下遍历 DOM 树的 jQuery 方法:

children()

find()


jQuery children() 方法

children() 方法返回被选元素的所有直接子元素。

该方法只会向下一级对 DOM 树进行遍历。

下面的例子返回每个 <div> 元素的所有直接子元素:

实例

<!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>

运行实例 »

点击 "运行实例" 按钮查看在线实例

您也可以使用可选参数来过滤对子元素的搜索。

下面的例子返回类名为 "1" 的所有 <p> 元素,并且它们是 <div> 的直接子元素:

实例

<!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":"red","border":"2px solid red"});
});
</script>
</head>
<body>

<div class="descendants" style="width:500px;">div (当前元素) 
  <p class="1">p (儿子元素)
    <span>span (孙子元素)</span>     
  </p>
  <p class="2">p (儿子元素)
    <span>span (孙子元素)</span>
  </p> 
</div>

</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


jQuery find() 方法

find() 方法返回被选元素的后代元素,一路向下直到最后一个后代。

下面的例子返回属于 <div> 后代的所有 <span> 元素:

实例

<!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>

运行实例 »

点击 "运行实例" 按钮查看在线实例

下面的例子返回 <div> 的所有后代:

实例

<!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("*").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>

运行实例 »

点击 "运行实例" 按钮查看在线实例