Div sum when parent div has more than 3 child divs
I have a simple HTML structure with elements div
. I want to find the sum of the values ββin the children div
for each parent div
, but only if the parent has at least three children.
This is what I tried, but it gets the sum from each div:
var sum = 0;
$("div > div > div").each(function () {
sum += parseInt($(this).text(), 10);
});
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- don't want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
</div>
So in the above example, Id will print the answer 8.
+3
source to share
2 answers
You can check each of these divs if the parent has more than 3 children:
var sum = 0;
$("div > div > div").each(function () {
if($(this).parent().children('div').length >3){
sum += parseInt($(this).text(), 10);
}
});
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- don't want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
</div>
<div>
<!-- want to calculate this --->
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
</div>
</div>
+5
source to share