Martin Martin - 1 year ago 131
Javascript Question

How do I get columns count in a table with rowspan/colspan in head?

How do I get columns count in a table with rowspan/colspan in head?

I need javascript/jQuery to get

for the following table:

<table border="1">
<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>
<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>

UPDATE: my personal solution is:

var max = 0;
var current = 0;
var colspan = $(this).attr('colspan');
current += Number(colspan ? colspan : 1);
max = Math.max(current, max);

UPDATE: To solve this problem we need to count
plus their
in the first row of
, 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.

Anybody can explain why my question is voted negatively?

Answer Source

reduce over the colspan info.

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

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download