JQuery add numbering to tds within a table row
function, javascript, jquery
Solution
Go by `tr` instead:
$('tr').each(function() {
$(this).children('td:contains(".")').each(function(i) {
$(this).addClass("reportcellno-" + i);
});
});
EDIT: less-loop way, but probably less readable:
$('tr td:contains(".")').each(function(){
$(this).addClass("reportcellno-" + (+$(this).index() + 1));
});
Here, we are using the fact that a `td` is a child of a `tr`, and `index()` returns the position of an element relative to its siblings.
From the docs:
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
Problem
I have come up with this function to add numbered classes to the elements within tables rows in my table: ``` $('tr td:contains(".")').each(function(i){ $(this).addClass("reportcellno-" + i); }); ``` Basically here, I am searching for any table cell with a decimal point and I want to interate through them within each row and add the class `reportcellno-1`, `reportcellno-2` This works pretty well and I have played around with it all day. The only issue is that the numbering goes on and on rather than limiting it by row. My output HTML code from the above is: ``` <tr> <td class="reportcellno-1">10.1</td> <td class="reportcellno-2">5.7</td> </tr> <tr> <td class="reportcellno-3">10.6</td> <td class="reportcellno-4">10.9</td> </tr> ``` Whereas I actually am trying to get this: ``` <tr> <td class="reportcellno-1">10.1</td> <td class="reportcellno-2">5.7</td> </tr> <tr> <td class="reportcellno-1">10.6</td> <td class="reportcellno-2">10.9</td> </tr> ``` So essentially for each table row, I want to start the numbering over. I am not even sure if this is possible.