Juri Juri - 3 days ago 5
jQuery Question

How to select only those elements with many children?

In jQuery, how can I select only the

div
that contains a specific number of
p
children, for example at least two?



$(".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>




Answer

You can use :has and :nth-child pseudo-class selectors. Although use direct child selector(>) to avoid nested children.

$(".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>


Or use filter() method and filter based on children count.

$(".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>

Comments