我需要得到所有后代的孩子,不仅仅是直接的孩子 我需要将属性css应用于元素p和元素span
<!DOCTYPE html>
<html>
<head>
<style>
.descendants * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/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 (current element)
<p>p (child)
<span>span (grandchild)</span>
</p>
<p>p (child)
<span>span (grandchild)</span>
</p>
</div>
</body>
</html>
答案 0 :(得分:3)
<script>
$(document).ready(function(){
$("div *").css({"color":"red","border":"2px solid red"});
});
</script>
编辑:根据评论澄清。
$("div p").css({"color":"red","border":"2px solid red"});
$("div span").css({"color":"red","border":"2px solid red"});
答案 1 :(得分:1)
而不是.children()
(只有...等待它......元素的子元素)而不是.find('*')
:
$(document).ready(function() {
$("div").find('*').css({
"color": "red",
"border": "2px solid red"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="descendants" style="width:500px;">div (current element)
<p>p (child)
<span>span (grandchild)</span>
</p>
<p>p (child)
<span>span (grandchild)</span>
</p>
</div>