FlyingCat
FlyingCat

Reputation: 14250

How to count the columns in my table

I am trying to count the total column of my table.

for example

   <table>
      <tr>
        <td>55</td>
        <td>22</td>
        <td>66</td>
      </tr>  
      <tr>
        <td>1</td>        
        <td>2</td>
        <td>3</td>        
      </tr>
   </table>

The above structure will give me 3 total columns.

I am also doing something for my td.

My codes are like

 $("table td").each(function(){
        codes to manipulate td...
 })

I was wondering if I can count the maximum column of my table in the above each codes.

Can anyone give me a hint? Thanks!

Upvotes: 1

Views: 134

Answers (5)

Mouad Debbar
Mouad Debbar

Reputation: 3226

The easiest, most performant and most reusable solution I could think of is:

function colCount($table) {
  return $table.find('tr').eq(0).children().length;
}

var cols = colCount($('table#myTable'));

Upvotes: 0

plalx
plalx

Reputation: 43718

thanks lbu, but I was hoping I can write some codes inside my each function

You can, but it's not as clean...

DEMO

var maxCols = 0,
    firstTr = $('table tr:first-child')[0];

$("table td").each(function() {
    var $this = $(this);

    if ($this.parent()[0] === firstTr) {
        maxCols += parseInt($this.attr('colspan'), 10) || 1;
    }
});

Note: This would account for colspans too.

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102753

The following will count the number of columns in the first row. It increments the count for those columns that are in the first row (determined using .index):

var cols = 0;
$("table td").each(function(){
    if ($(this).closest("tr").index() == 0) cols++;
})

(Fiddle)


The following counts the maximum number of columns in the table (useful if the rows have variable column counts):

var maxColumns = Math.max.apply(null, $("table tr").map(function() { 
    return $(this).find("td").length; 
}));

(Fiddle)

Upvotes: 1

ScalaWilliam
ScalaWilliam

Reputation: 741

Math.max.apply(null, $("table tr").map(function(_,row) { return $(row).find("td").length; }))

Upvotes: 1

Ibu
Ibu

Reputation: 43810

$("table td").length will return all the columns on the table which is (6) not what you want.

$("table tr:eq(0) td").length, will give you the number of columns in the first row.

Upvotes: 2

Related Questions