sova
sova

Reputation: 5650

How can I find the largest table cell height with jQuery?

I have a table with cells of variable-length text-content. I want to find the height of the tallest cell and then make all the cells that height. How can I do this?

Upvotes: 8

Views: 11461

Answers (5)

John Strickler
John Strickler

Reputation: 25421

Just to be different:

var heights = $('td').map(function() {
    return $(this).height();
}).get();

var maxHeight = Math.max.apply(Math, heights);

$('td').css('height', maxHeight);

Upvotes: 3

Hedde van der Heide
Hedde van der Heide

Reputation: 22459

contribute @tatu ulmanen's example

This is obvious but if you just want to strech the rows with taller cells wrap a tr loop :)

$('table tr').each(function (){
    var max = 0;
    $(this).find('td').each(function (){
        max = Math.max($(this).height(), max);
    }).height(max);
});

Upvotes: 0

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124828

Like this:

var max = 0;    
$('table td').each(function() {
    max = Math.max($(this).height(), max);
}).height(max);

In plain english, loop through all the cells and find the maximum value, then apply that value to all the cells.

Upvotes: 27

Ehsan
Ehsan

Reputation: 1682

You can use jQuery with the following code


var maxHeight = 0;
$('#yourTableID td').each(function(index, value)
{
if ($(value).height() > maxHeight)
maxHeight = $(value.height());
}).each(function(index, value) {
$(value).height() = maxHeight;
});

Hope it helps

Upvotes: -1

Jason McCreary
Jason McCreary

Reputation: 73021

There are several plugins that can do this for you. However, the code would look like this:

var tallest = 0;
$('table td').each(function() {
  if (tallest < $(this).height()) {
    tallest = $(this).height();
  }
});

$('table td').css({'height': tallest});

Upvotes: 0

Related Questions