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="https://cdn.bootcss.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>
效果:
这里的两个p标签是div的直接子元素,而里面的span则是间接的子元素,所以没有变色