JQuery adds numbering to tds in table row

I came up with this function to add numbered classes to elements in row rows in my table:

$('tr td:contains(".")').each(function(i){ $(this).addClass("reportcellno-" + i); }); 

Basically, here I am looking for any table cell with a decimal point, and I want to interact through it in each row and add the class reportcellno-1 , reportcellno-2

It works very well, and I played with him all day. The only problem is that numbering continues and continues, rather than restricting it to a line.

My HTML output is from the above:

 <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> 

While I'm really 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 row of the table, I want to start numbering. I'm not even sure that this is possible.

+4
source share
2 answers

Go to tr instead:

 $('tr').each(function() { $(this).children('td:contains(".")').each(function(i) { $(this).addClass("reportcellno-" + i); }); }); 

EDIT: a method with a smaller loop, but probably less readable:

 $('tr td:contains(".")').each(function(){ $(this).addClass("reportcellno-" + (+$(this).index() + 1)); });​ 

Here we use the fact that a td is a child of tr , and index() returns the position of the element relative to its siblings.

From docs :

If no argument is passed to the .index () method, the return value is an integer indicating the position of the first element within jQuery relative to its sibling elements.

+6
source

Simple js solution numbered with lines:

 var rows = document.getElementsByTagName('tr'); for (var j=0, jLen=rows.length; j<jLen; j++) { var cell, cells = rows[j].getElementsByTagName('td'); for (var i=0, iLen=cells.length, c=0, txt; i<iLen; i++) { cell = cells[i]; txt = cell.innerText || cell.textContent; if ( txt.indexOf('.') > -1) { cell.className = cell.className + ' reportcellno-' + c++; } } } 

Numbered through the table:

 var cell, cells = document.getElementsByTagName('td'); for (var i=0, iLen=cells.length, c=0, txt; i<iLen; i++) { cell = cells[i]; txt = cell.innerText || cell.textContent; if (txt.indexOf('.') > -1) { cell.className = cell.className + ' reportcellno-' + c++; } } 
0
source

Source: https://habr.com/ru/post/1411673/


All Articles