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>
      

Run codeHide result


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>
      

Run codeHide result


+5


source


give parent divs a class, let's call it .parent

:



var sum = 0;
$(".parent").each(function () {
    if($(this).children('div').length>3){
        $(this).children('div').each(function(){
           sum += parseInt($(this).text(), 10); 
        });
    }
});

console.log(sum);

      

0


source







All Articles