Shrout1
Shrout1

Reputation: 2607

Uniquely identify HTML table in order to count columns

I need to append columns to an HTML table in a specific location. This topic discusses doing that - pretty handy! My problem is that the columnCount() function shown below does not have the ability to target a specific table. It counts all TDs present in the HTML which ends up causing problems when generating an index value.

function countColumn() {
   var colCount = 0;
   $('tr:nth-child(1) td').each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
}

I have two JS fiddles.

Edit: Link to the JSFiddle that has the corrected code. I hope this helps someone else who is struggling with selector syntax!

Upvotes: 0

Views: 359

Answers (1)

Barmar
Barmar

Reputation: 781503

Take the table ID as a parameter:

function countColumn(tableID) {
   var colCount = 0;
   $('#' + tableID + ' tr:nth-child(1) td').each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
}

You could also define a jQuery method that operates on a selector:

$.fn.colCount = function() {
   var colCount = 0;
   $('tr:nth-child(1) td', this).each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
};

Then you can do var count = $("#someTable").colCount();

Upvotes: 1

Related Questions