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

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>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top