在jQuery中,我如何只选择包含特定数量的p个子节点的div,例如至少两个? $(".myDiv").css("background-color", "yellow"); div { border:1px solid black;} script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquer
$(".myDiv").css("background-color", "yellow");
div { border:1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="myDiv"> <p class="my_p">1</p> </div> <div class="myDiv"> <p class="my_p">1</p> <p class="my_p">2</p> </div> <div class="myDiv"> <p class="my_p">1</p> <p class="my_p">2</p> <p class="my_p">3</p> </div>您可以使用
:has
和
:nth-child
伪类选择器.虽然使用
direct child selector(>
)来避免嵌套的孩子.
$(".myDiv:has(>:nth-child(2))").css("background-color", "yellow");
div { border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="myDiv"> <p class="my_p">1</p> </div> <div class="myDiv"> <p class="my_p">1</p> <p class="my_p">2</p> </div> <div class="myDiv"> <p class="my_p">1</p> <p class="my_p">2</p> <p class="my_p">3</p> </div>
或者使用filter()
方法并根据子计数进行过滤.
$(".myDiv").filter(function() { return $(this).children().length > 1; }).css("background-color", "yellow");
div { border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="myDiv"> <p class="my_p">1</p> </div> <div class="myDiv"> <p class="my_p">1</p> <p class="my_p">2</p> </div> <div class="myDiv"> <p class="my_p">1</p> <p class="my_p">2</p> <p class="my_p">3</p> </div>