user70192
user70192

Reputation: 14204

jQuery - Get Tallest Column in Row

I have a page that uses Bootstrap. I am trying to find the height of the largest column within each row. In an attempt to do this, I have:

html:

<div class="row">
  <div class="col-md-4">
    <br />
    One
  </div>
  <div class="col-md-4">
    <br />
    <br />
    <br />
    Two
  </div>
  <div class="col-md-4">
    <br />
    Three
  </div>
</div>

<div class="row">
  <div class="col-md-4">
    <br />
    One
  </div>
  <div class="col-md-4">
    <br />
    <br />
    Two
  </div>
  <div class="col-md-4">
    <br />
    <br />
    <br />
    Three
  </div>
</div>


javascript:

$(function () {
  var rows = $('.row');
  for (var i = 0; i < rows.length; i++) {
    var maxHeight = 0;

    var cols = null;  // NOT SURE WHAT TO DO TO GET THE COLUMNS HERE
    for (var i2 = 0; i2 < cols.length; i2++) {
      var colHeight = $(cols[i2]).height();     // NOT SURE IF THIS IS CORRECT
      if (colHeight > maxHeight) {
        maxHeight = colHeight;
      }
    }

    alert('Largest Column Height: ' + maxHeight);
  }
});

jsfiddle here

I'm not sure how to get all of the columns within a given row. At that point, I'm not entirely sure how to get the height. These are both rooted in the same problem: I don't understand when to use a selector and when not to.

How do I get all of the columns in a row and their respective heights?

Upvotes: 2

Views: 665

Answers (1)

Carlos487
Carlos487

Reputation: 1489

To select the columns you need to use:

var cols = $(rows[i]).children('div');

The trick is that you always need to make the variable inside the for a jquery variable with $(variable) then you search for the children div.

The full code is:

$(function () {
  var rows = $('.row');
  for (var i = 0; i < rows.length; i++) {

    var maxHeight = 0;

    var cols = $(rows[i]).children('div');  // NOT SURE WHAT TO DO TO GET THE COLUMNS HERE
    for (var i2 = 0; i2 < cols.length; i2++) {
      var colHeight = $(cols[i2]).height();     // NOT SURE IF THIS IS CORRECT
      if (colHeight > maxHeight) {
        maxHeight = colHeight;
      }
    }

    alert('Largest Column Height: ' + maxHeight);
  }
});

https://api.jquery.com/children/

Upvotes: 1

Related Questions