Andrew Andrew - 6 months ago 30
Javascript Question

jQuery: How to count table columns?

Using jQuery, how would you figure out how many columns are in a table?

<script>
alert($('table').columnCount());
</script>

<table>
<tr>
<td>spans one column</td>
<td colspan="2">spans two columns</td>
<td colspan="3">spans three columns</td>
<tr>
</table>


The total number of columns in this example is 6. How could I determine this using jQuery?

Answer

Here you go:

jsFiddle

$(function() {
    var colCount = 0;
    $('tr:nth-child(1) td').each(function () {
        if ($(this).attr('colspan')) {
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
});