jQuery: How to count table columns?

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