user1596316 user1596316 - 4 months ago 10
jQuery Question

Find element by child count

Is there a method using jquery or xpath to select an element that has fewer than n children ?

so given:

<div id="1" class="parent">
<div class="child></div>
<div class="child></div>
</div>
<div id="2" class="parent">
<div class="child></div>
<div class="child></div>
<div class="child></div>
</div>
<div id="3" class="parent">

</div>


I would want all the parents with fewer than 3 child divs, id 1 and 3

Answer

This XPath should select what you want:

//div[@class = 'parent' and 3 > count(div)]
Comments