Skip to content
Advertisement

Continue loop through all tbody element and add id to all tr’s

I have many tables and I want to give all tr’s individual ids. I loop through all tbody but it only affects first tbody, not all of them. When I add loop indicating each tbody they work. Is there any efficient way available to loop through all tbody and give the tr’s individual id. I want to do it using vanilla javascript, no jQuery.

My sample code here :

<table><tbody>
<tr><td>No.</td><td>Name</td><td>Score</td></tr>
<tr><td>01</td><td>ted</td><td>0.50</td></tr>
<tr><td>02</td><td>joe</td><td>0.25</td></tr>
</tbody></table>
<table><tbody>
<tr><td>Name</td><td>Address</td><td>Phone</td></tr>
<tr><td>joe</td><td>LA</td><td>012345</td></tr>
<tr><td>ted</td><td>NY</td><td>0124</td></tr>
</tbody></table>
<table><tbody>
<tr><td>Name</td><td>Spec</td><td>Budget</td></tr>
<tr><td>joe</td><td>i5</td><td>458</td></tr>
<tr><td>ted</td><td>i7</td><td>768</td></tr>
</tbody></table>

Javascript :

var c = document.getElementsByTagName('tbody');
var _trIndex = 1;

for ( i=0; i<c.length; i++) {
  var x = c[i].rows; 
  for (i=0; i<x.length; i++){
    x[i].setAttribute('id','tr'+_trIndex++)
  }
}

Second Try :

var c = document.getElementsByTagName('tbody');
var _trIndex = 1;

for ( i=0; i<c.length; i++) {
  var x = c[0].rows; 
  for (i=0; i<x.length; i++){
    x[i].setAttribute('id','tr'+_trIndex++)
  }
  var y = c[1].rows;
  for (i=0; i<y.length; i++){
    y[i].setAttribute('id','tr'+_trIndex++)
  }
}

Advertisement

Answer

Probably this is what you need:

// Instead of getting the table bodies, I get only the table 
// rows inside the tbody elements.
var c = document.querySelectorAll('tbody tr');

// Here I check if definitely the above query found any values.
if ( c ) {
  // Then I do the itteration to the found tr elements
  for ( i = 0; i < c.length; i++) {
    // And here I set the ID the same way you did in your example
    c[i].setAttribute('id','tr'+i);
  }
}
<table>
  <tbody>
    <tr><td>No.</td><td>Name</td><td>Score</td></tr>
    <tr><td>01</td><td>ted</td><td>0.50</td></tr>
    <tr><td>02</td><td>joe</td><td>0.25</td></tr>
  </tbody>
</table>

<table>
  <tbody>
    <tr><td>Name</td><td>Address</td><td>Phone</td></tr>
    <tr><td>joe</td><td>LA</td><td>012345</td></tr>
    <tr><td>ted</td><td>NY</td><td>0124</td></tr>
  </tbody>
</table>
<table>
  <tbody>
    <tr><td>Name</td><td>Spec</td><td>Budget</td></tr>
    <tr><td>joe</td><td>i5</td><td>458</td></tr>
    <tr><td>ted</td><td>i7</td><td>768</td></tr>
  </tbody>
</table>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement