5

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.

santa
  • 12,234
  • 49
  • 155
  • 255
  • 3
    Walk through each using `each()`, and check each's `width()`. I don't think there is an easier way – Pekka Aug 30 '11 at 16:39
  • 1
    Wouldn't all first column td elements in a table be the same width? Are you looking for the width of something inside the td elements? – jfriend00 Aug 30 '11 at 16:49
  • This is where having a `.reduce()` function, as well as `.map()` would be useful in jQuery. – Orbling Aug 30 '11 at 16:51
  • @jfriend00 Good point (I asked the same question below :) ). – jensgram Aug 31 '11 at 06:12

5 Answers5

4
var w = 0;
$("#myTable tr td:first").each(function(){
    if($(this).width() > w){
        w = $(this).width();
    }
});
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
4

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());
});
jensgram
  • 31,109
  • 6
  • 81
  • 98
2

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());
});
yoozer8
  • 7,361
  • 7
  • 58
  • 93
2
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);
Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
0

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()
     }
});
Rion Williams
  • 74,820
  • 37
  • 200
  • 327