Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a table's column count 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)?

like image 746
mano Avatar asked Dec 03 '22 01:12

mano


2 Answers

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;
like image 200
senK Avatar answered Dec 14 '22 09:12

senK


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;
}
like image 22
Tim Down Avatar answered Dec 14 '22 09:12

Tim Down