Skip to content
Advertisement

How do I get the column count of a table when there are cells with rowspan/colspan?

How do I get the column count of a table when there are cells with rowspan/colspan?

UPDATE: In this question I mean the classical (as far as I know) use of tables, when it’s necessary to use the colspan, though it’s not required by the specification (and table will look ugly but it will be valid).

I need JavaScript/jQuery to get 11 for the following table (as 11 is the maximum number of columns for this table):

<table border="1">
    <thead>
        <tr>
            <th rowspan="3">Lorem</th>
            <th rowspan="3">ipsum</th>
            <th rowspan="3">dolor</th>
            <th colspan="4">sit</th>
            <th colspan="4">amet</th>
        </tr>
        <tr>
            <th colspan="3">consectetur</th>
            <th rowspan="2">adipisicing</th>
            <th rowspan="2">elit</th>
            <th rowspan="2">sed</th>
            <th rowspan="2">do</th>
            <th rowspan="2">eiusmod</th>
        </tr>
        <tr>
            <th>tempor</th>
            <th>incididunt</th>
            <th>ut</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

https://jsfiddle.net/toahb3a3/

My personal solution is:

$(function(){
  var max = 0;
  $('tr').each(function(){
    var current = 0;
    $(this).find('th').each(function(){
      var colspan = $(this).attr('colspan');
      current += Number(colspan ? colspan : 1);
    });
    max = Math.max(current, max);
  });
  console.log(max);
});

https://jsfiddle.net/mt7qhbqd/

UPDATE: To solve this problem we need the sum of th elements plus their colspan in the very first row of thead. Thanks to Andy for his code, it’s really compact and it gave me the thought that I need only the first row. Also, thanks to Quentin who pointed me to the case when colspan is not necessarily used, so Andy’s alogrithm won’t work (but Quentin’s will). Also thanks to Quentin for helping me with the title, as my English isn’t good enough.

Advertisement

Answer

reduce over the colspan info.

var th = document.querySelectorAll('table thead tr:first-child th');

var cols = [].reduce.call(th, function (p, c) {
  var colspan = c.getAttribute('colspan') || 1;
  return p + +colspan;
}, 0);

DEMO

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement