jQuery 遍历后代
使用jQuery,我们可以沿着DOM树向下遍历,寻找一个元素的后代。
后裔是指孩子、孙子、曾孙等等。
DOM树下的遍历:jQuery用于DOM树下的遍历方法有。
- children()
- find()
jQuery children()方法
children()方法返回选定元素的所有直接子女。
这种方法只对DOM树进行单层的追踪。
示例:
<!DOCTYPE html>
<html>
<head>
<style>
.descendants * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
("div").children().css({
"color": "green",
"border": "2px solid blue"
});
});
</script>
</head>
<body>
<div class="descendants"
style="width:500px;">
current element
<p>child
<span>
grandchild
</span>
</p>
</div>
</body>
</html>
输出:
jQuery find()方法
jQuery find()方法返回所选元素的后裔元素,一直到最后的后裔。
示例-2:
<!DOCTYPE html>
<html>
<head>
<style>
.descendants * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
("div").find("span").css({
"color": "green",
"border": "2px solid blue"
});
});
</script>
</head>
<body>
<div class="descendants"
style="width:500px;">
current element
<p>child
<span>grandchild</span>
</p>
</div>
</body>
</html>
输出: