The table in our HTML web pages are very important: we can use them for manage our layout, show the data and a lot of other possibilietis. So, it is possible we have to count the rows and the columns, two easy operations, but maybe the count of columns is not so intuitive at first impact.

Counting rows

Here a little and simple code for counting the rows in an HTML table, with JQuery

$('#myTable tr').length;

and without it:

document.getElementById(tableId).getElementsByTagName("tr").length;

Or if there’s a

in between,

document.getElementById(tableId).getElementsByTagName("tbody")[0].getElementsByTagName("tr").length;

Counting columns

The count of the columns is little little little bit less easy. Here the snippet with JQuery:

var columnCount = jQuery(‘#myTable ’).find(‘tr’)[0].cells.length;

and without it:

document.getElementById('table1').rows[0].cells.length

Or if there’s a

in between,

document.getElementById(tableId).getElementsByTagName("tbody")[0].rows[0].cells.length;

So, the idea for count the columns is to get the first row and count its cells. You have to do in this way, because there is still no method like MyTable.columns.

Advertisements