Question

I have a problem with javascript.
I have a list of table cells stored at TabList.
I want to find the maximum width, and then set this width to all of them.
A sample code is here, but the setting of the width is not working.

var MaxTabWidth = 0;
for (var i = 0; i < TabList.length-1; i++)
{
  if (TabList[i].offsetWidth>MaxTabWidth) 
    MaxTabWidth = TabList[i].offsetWidth;
}

for (var i = 0; i < TabList.length-1; i++)
{
  TabList[i].style.width = MaxTabWidth+"px";
  // TabList[i].width = MaxTabWidth+"px";
  // TabList[i].offsetWidth = MaxTabWidth+"px";
}

I have commented my attempts..
Any help?
This didn't do the trick for me..

update:
I am sure TabList is a list of Cells because I was checking the className.
I am looping until TabList.length-1, because I want the last cell to fill the rest of the table's width.

Was it helpful?

Solution

I would suggest you remove all css/styling from the page and testing it to isolate the problem. Things like this are often complicated by css.

OTHER TIPS

If you set the width of the entire table to --i*MaxTabWidth. Would that evenly distribute the columns? Suppose your table is named myTable.

document.getElementById('myTable').width = new String(--i*MaxTabWidth)

Edit: Also wouldn't

for (var i = 0; i < TabList.length-1; i++)

skip the last column by stopping at TabList.length-2?

For what it is worth, in jQuery this can be done with the following script where your table has the id of "myTable". If you have enough control over the environment to add in a framework, I would highly recommend it since it makes tasks like these much easier.

    var maxWidth = 0;

    $("#myTable td").each(function() {
        if ($(this).width() > maxWidth) {
            maxWidth = $(this).width();
        }
    });
    $("#myTable td").width(maxWidth);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top