Get div height using jQuery selector?

Viewed 260

I have a table which has many rows and 3 columns. Each column has div inside. I want to get the height of the div in the 2nd column. I gave jQuery as under:

$('#elementId tbody tr td.elment-class-2 div').height(); // works good, returns height of first rows div

Now, I want to run this in a loop so get the height of div present in all rows in 2nd column. So I wrote planned this code:

var count = $('#elementId tbody tr td.elment-class-2 div').length;
    $('#elementId tbody tr td.elment-class-2 div')[0]; //
    $('#elementId tbody tr td.elment-class-2 div')[1]; // and so on in a loop

But this returns error

$('#elementId tbody tr td.elment-class-2 div')[0]; // Uncaught TypeError: $(...)[0].height is not a function

P.S: Newbie to jQuery here. Pardon my foolish mistakes.

2 Answers

The problem is that the values returned from the jQuery selector are not an array, so you cannot loop through them like an array. You need to use the each() jQuery function to do this.

You can do this like follows:

$('#elementId tbody tr td.elment-class-2 div').each(function(i, ) { 
    divHeight = $(divToCheck).height(); 
});

The i is the index of the (Note also that you are unlikely to need such specificity in your selector - it can make the code less reusable and more difficult to maintain)

Without your original HTML, I can only show you a generic example of this working below:

$('tr div').each(function(i, divToCheck) {
  divHeight = $(divToCheck).height();
  console.log("Div "+ i + " height = "+ divHeight);
});
td { border:1px solid grey;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><div>hello</div></td>
  </tr>
  <tr>
    <td><div style="height:30px;">hello </div></td>
  </tr>
  <tr>
    <td>
      <div style="font-size:20px">hello</div>
    </td>
  </tr>
</table>

I checked your CodePen and it seems that for variable ht there is a typo, the class needs to be next to the TD ie td.elmCls and for the second part here is the code:

$(document).ready(function () {
  var ht = $('table tbody tr td.elmCls').height();
  console.log(ht)

  var divs = $('tbody tr td:nth-of-type(2) div');
  divs.each(function(index, elem) {
   console.log(elem.innerText);
   var height = $(elem).height();
   console.log(height);
  });
});

The reason why you see that error is because when you try to get an object via $() method it will initially return a jQuery object. When you then use [0] on the object like $('td.elmCls')[0] you then get back a native Javascript node/element. That node does not have a height() method on it and this is why you get that error.

You resolve this by using the .each(function(index, element){ [code-here]}) method and then simply printing element.innerText out to the console.

Related