santa
santa

Reputation: 12512

detect the widest cell w/ jQuery

I have a table with different values. First column contains labels. I need to get the width of the widest label. I assume I need some sort of a loop, but then what?

$("#myTable td:nth-child(1)").width();

Thanks.

Upvotes: 5

Views: 2338

Answers (5)

jensgram
jensgram

Reputation: 31498

I assume that you have one <label> element inside all <td> elements in the first column (since it makes no sense to compare the widths of the <td> elements themselves — within the same column they are equally wide (not considering colspan != 1)):

var widestLabel = 0;
$("#myTable td:nth-child(1) label").each(function() {
    widestLabel = Math.max(widestLabel, $(this).width());
});

Upvotes: 4

Simon Arnold
Simon Arnold

Reputation: 16177

var widestTdLabel=0;
$('#myTable td').each(function(index) { 
    if($(this).find('label').width()>widestTdLabel)
        widestTdLabel=$(this).find('label').width();
});
alert(' width of the widest label is:'+widestTdLabel);

Upvotes: 2

yoozer8
yoozer8

Reputation: 7489

Try this:

var widest;
var widestWidth = 0;
$("#myTable td").each(function(t) {
    if($(this).width() > widestWidth){
        widest = $(this);
        widestWidth = $(this).width();
    }
});
//Now widest points to the widest element

Note I tracked the actual width separately from the widest element. An alternate solution without this method would be to initialize widest to a dummy element with width = 0 and just compare $(this).width() with widest.width()

EDIT: Or, alternately, now that I realize you wanted only the width and not the actual element, you could use this version:

var widestWidth = 0;
$("#myTable td").each(function(t) {
     widestWidth = Math.max(widestWidth, $(this).width());
});

Upvotes: 2

Rion Williams
Rion Williams

Reputation: 76577

This should work - it will go through each of the tds (in myTable) and find the widest:

var widest = 0;
$("#myTable tr td:first").each(function()
{
     widest = ($(this).width() > widest) : $(this).width() : widest;
});

alternatively:

var widest = 0;
$("#myTable tr td:first").each(function()
{
     if($(this).width() > widest){
         widest = $(this).width()
     }
});

Upvotes: 0

Marek Sebera
Marek Sebera

Reputation: 40661

var w = 0;
$("#myTable tr td:first").each(function(){
    if($(this).width() > w){
        w = $(this).width();
    }
});

Upvotes: 4

Related Questions