0

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.

  • One functions because there is only one table.
  • The second one does not function because there are two tables present.

    The second fiddle returns an invalid colCount value and cannot place the column inside of the target table. I am still too green on selectors to be able to apply the correct selector in context... I am slowly learning this language.

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

Community
  • 1
  • 1
Shrout1
  • 2,497
  • 4
  • 42
  • 65

1 Answers1

1

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();

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Excellent! Thank you so much! I've been struggling with selector syntax. Are there any good resources that outline how to select specific DOM elements - I find that I get lost without solid examples. – Shrout1 Jun 09 '13 at 15:17
  • Thank you for humoring a newb :) Can't tell you how much I appreciate the help. – Shrout1 Jun 09 '13 at 16:04