Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 450
Andrew Avatar asked Jul 13 '11 18:07

Andrew


People also ask

How can I get table Tbody row count in jQuery?

Answer: Use the length Property You can simply use the length property to count or find the number of rows in an HTML table using jQuery. This property can be used to get the number of elements in any jQuery object.

How can count TD table in jQuery?

columnCount = function() { return $('th', $(this). find('tbody')). length; }; var rowctr = $('#table1'). rowCount(); var colctr = $('#table1').

How can get TD of TR in jQuery?

jQuery(". dname"). find("tr td:eq(1)"). val();


2 Answers

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++;         }     }); }); 
like image 143
Craig M Avatar answered Sep 30 '22 12:09

Craig M


$("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++;    } } 
like image 30
scrappedcola Avatar answered Sep 30 '22 12:09

scrappedcola