rsk82
rsk82

Reputation: 29387

how to check with javascript how many columns given html table has?

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

Upvotes: 1

Views: 10358

Answers (4)

brymck
brymck

Reputation: 7663

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);

Upvotes: 2

Abdulsattar Mohammed
Abdulsattar Mohammed

Reputation: 10722

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;
}

Upvotes: 1

James Allardice
James Allardice

Reputation: 165991

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);

Upvotes: 1

Pointy
Pointy

Reputation: 413757

  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.

Upvotes: 3

Related Questions