Andrew Andrew - 4 months ago 9
HTML Question

How can I select descendents of each instance of a class?

Here’s a simplified version of my code.

<div class="row">
<div class="column">

</div>
<div class="column">

</div>
</div>
<div class="row">
<div class="column">

</div>
</div>
<div class="row">
<div class="column">

</div>
<div class="column">

</div>
<div class="column">

</div>
</div>


I’m trying to add the heights of every “column” DIV within each “row” DIV. In other words, I want to add the two “column” DIVs in the first “row” DIV; the one “column” DIV in the second “row” DIV; and the three “column” DIVs in the third “row” DIV. How can I do this?

Answer

If I understand what you are asking...

// Loop through each .row...
$('.row').each(function(i) {
  var totalHeight = 0;

  // Loop though descendant .column's in this .row...
  $(this).find('.column').each(function() {

    // Add .column height to total...
    totalHeight += $(this).height();
  })

  // do something with the total...
  console.log('columns in row ' + i + ' have a total height of ' + totalHeight + 'px');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="row">
  <div class="column">
    Column
  </div>
  <div class="column">
    Column
  </div>
</div>
<div class="row">
  <div class="column">
    Column
  </div>
</div>
<div class="row">
  <div class="column">
    Column
  </div>
  <div class="column">
    Column
  </div>
  <div class="column">
    Column
  </div>
</div>