Martin Martin - 7 months ago 23
Javascript Question

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?

I need JavaScript/jQuery to get

11
for the following 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/

UPDATE: 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 to count
th
plus their
colspan
in the first row of
thead
, because the first row should contain all the columns even if they're row/colspaned. Thanks Andy for his code, it's really compact and it gave me the thought that I need only first row.

Can anybody explain why my question is voted negatively? What's wrong with it

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