Skip to content Skip to sidebar Skip to footer

Jquery: How To Count Table Columns?

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

Solution 1:

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++;
        }
    });
});

Solution 2:

$("table").find("tr:first td").length;

I edited as I didn't realize you were counting the colspan's.

If you want to include using colspan try a loop through the td's in the first row:

var cols = $("table").find("tr:first td");
var count = 0;
for(var i = 0; i < cols.length; i++)
{
   var colspan = cols.eq(i).attr("colspan");
   if( colspan && colspan > 1)
   {
      count += colspan;
   }else{
      count++;
   }
}

Solution 3:

This is the cleanest in my opinion. It handles tables within tables. And is short and simple:

$("table > tbody > tr:first > td").length

Solution 4:

To be robust..I'd do something like this

alert(numCol("table") + " is the max number of cols");

functionnumCol(table) {
    var maxColNum = 0;

    var i=0;
    var trs = $(table).find("tr");

    for ( i=0; i<trs.length; i++ ) {
        maxColNum = Math.max(maxColNum, getColForTr(trs[i]));
    }

    return maxColNum;
}

functiongetColForTr(tr) {

    var tds = $(tr).find("td");

    var numCols = 0;

    var i=0;
    for ( i=0; i<tds.length; i++ ) {
        var span = $(tds[i]).attr("colspan");

        if ( span )
            numCols += parseInt(span);
        else {
            numCols++;
        }
    }
    return numCols;
}

Just in case we have some funkiness going on between different rows.

Solution 5:

http://jsfiddle.net/WvN9u/

Just paying attention to colspan attr

Post a Comment for "Jquery: How To Count Table Columns?"