For row count using DOM, we have tablename.rows.length to get number of rows, but we don't have 'cols.length' for column count.
How can we find the number of columns (only using the DOM)?
For row count using DOM, we have tablename.rows.length to get number of rows, but we don't have 'cols.length' for column count.
How can we find the number of columns (only using the DOM)?
I think you can use cells to calculate the column, assuming that the number of column of first row will be same for all
tablename.rows[0].cells.length;
I would use the table's rows
property and the first row's cells
property and total the colSpan
property of each cell in the row. This will work in all major browsers back to IE 4 and should be pretty fast.
Demo: http://jsfiddle.net/Gtdru/
Code:
function getTableColumnCount(table) {
var columnCount = 0;
var rows = table.rows;
if (rows.length > 0) {
var cells = rows[0].cells;
for (var i = 0, len = cells.length; i < len; ++i) {
columnCount += cells[i].colSpan;
}
}
return columnCount;
}
There isn't such a concept in the DOM.
You could try and count the max number of td
and th
in tr
:
var max = 0;
$('#tableId tr').each(function(){max=Math.max(max, $('td,th', this).length)});
If you want to take into account the colspan, it's a little heavier :
var max = 0;
$('#tableId tr').each(function(){
var inTr = 0;
$('td,th', this).each(function() { inTr += parseInt($(this).attr('colspan')) || 1;});
max = Math.max(max,inTr);
});
This will work with complex table headers :
$($('#table_id_here tbody tr')[0]).find('td').length
A very simple way to get the number of possible cols in any table is using the following (vanillaJS) function:
/**
* Calculates the number of columns based on any row using colSpan attribute.
*
* @param {HTMLElement} table : The table element to be count.
*
* @return {int} The number of columns this table has.
*/
var getTableColSpan = function getTableColSpan(table) {
var colSpan = 0; // initialize counter
var trs = table.querySelectorAll('tr'); // get firt tr cells.
for (var j = 0; j < trs.length; j++) {
var tr = trs[j];
var tds = tr.cells;
var trColSpan = 0; // initialize counter
// loops between columns and gets each one's colSpan
for (var i = 0; i < tds.length; ++i) {
trColSpan += tds[i].colSpan;
}
colSpan = trColSpan > colSpan ? trColSpan : colSpan;
}
return colSpan;
};