1

That is how is the maximum colspan, for example:

<table>
 <tr>
  <td> 1 </td>
  <td> 2 </td>
  <td> 3 </td>
 </tr>
 <tr>
  <td> 1 </td>
  <td> 2 </td>
 </tr>
 <tr>
  <td> 1 </td>
 </tr>
</table>

should give 3

rsk82
  • 28,217
  • 50
  • 150
  • 240
  • plain JS or using a particular framework (jQuery/mootools/etc) ? – stecb Jun 15 '11 at 15:34
  • 1
    Shouldn't each table row have the same number of columns? Or at least a colspan on the cell(s) of the row with the fewest columns? – jszpila Jun 15 '11 at 15:41
  • I prefer plain JS. Sorry for not specyfying. – rsk82 Jun 15 '11 at 15:42
  • @Jan That's what I was thinking. If this is the asker's website, he should probably fix things such that all rows have the [same number of columns](http://www.w3.org/TR/html4/struct/tables.html). If it's not, of course, this is the right way to go about it. – brymck Jun 15 '11 at 15:47
  • I also found that `colspan='100%'` sets the `` tag do maximum available colspan. -> here http://stackoverflow.com/questions/398734/colspan-all-columns – rsk82 Jun 16 '11 at 12:09

4 Answers4

3
  1. Find each <tr> with "getElementsByTagName()"
  2. For each <tr>, find each <td> similarly
  3. Count the <td> elements, then iterate through and add "colspan - 1" for each <td> with a "colspan" attribute
  4. Maintain a maximum count over all rows.
Pointy
  • 405,095
  • 59
  • 585
  • 614
2

See this jsFiddle for an example. As you requested, it's in plain JavaScript:

var table = document.getElementById("myTable");
var max = 0;

for (var i = 0, iLen = table.rows.length; i < iLen; i++) {
  var temp = 0;
  var cells = table.rows[i].cells;

  for (var j = 0, jLen = cells.length; j < jLen; j++) {
    // This is very important. If you just take length you'll get the
    // the wrong answer when colspan exists
    temp += cells[j].colSpan;
  }

  if (temp > max) {
    max = temp;
  }
}

alert(max);
brymck
  • 7,555
  • 28
  • 31
1

See this fiddle for a jQuery version. It counts the number of td elements in each tr and checks each time to see if a greater number has been encountered. The max variable stores the current maximum number of columns found:

var max = 0;
$("tr").each(function() {
   var count = $(this).find("td").length;
    if(count > max) max = count;
});
alert(max);
James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

Each table has a rows array, and each row has a cells array. Then it's just a matter a finding the maximum.

function calculateCells(){
    var table = document.getElementById("table");
    var max = 0;
    for(var i=0;i<table.rows.length;i++) {
        if(max < table.rows[i].cells.length)
            max = table.rows[i].cells.length;
    }
    return max;
}
Abdulsattar Mohammed
  • 10,154
  • 13
  • 52
  • 66