Reputation: 2607
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.
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!
Upvotes: 0
Views: 359
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