Andrew Andrew - 1 year ago 135
Javascript Question

jQuery: How to count table columns?

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


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

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

Answer Source

Here you go:


$(function() {
    var colCount = 0;
    $('tr:nth-child(1) td').each(function () {
        if ($(this).attr('colspan')) {
            colCount += +$(this).attr('colspan');
        } else {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download