We help IT Professionals succeed at work.

How to cycle through TR tags in TABLE

Valimai
Valimai asked
on
hi there,

I have the following table
<table id="mytable">
      <tr id="myHeader">
            <th">ID</th>
            <th">Value</th>
      </tr>
      <tr id="row_0">
            <td>value_0</td>
            <td>display_0</td>
      </tr>
      <tr id="row_1">
            <td>value_1</td>
            <td>display_1</td>
      </tr>
      <tr id="row_2">
            <td>value_2</td>
            <td>display_2</td>
      </tr>
      <tr id="row_3">
            <td>value_3</td>
            <td>display_3</td>
      </tr>
      <tr id="row_4">
            <td>value_4</td>
            <td>display_4</td>
      </tr>
      <tr id="row_5">
            <td>value_5</td>
            <td>display_5</td>
      </tr>
</table>

How with javascript can i cycle through the rows? I wish to apply a background style on some rows.

I have tried various methods which i wont post here to clutter. I prefer a solution which does not cycle through all controls on the page, rather, just the rows of this table if possible.

This is for an intranet which is IE only, so an IE solution is fine.

thanks!
Comment
Watch Question

CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008

Commented:
var tbl = document.getElementById("myTable");
var thead = tbl.firstChild;//IE implicitly adds thead element
var tr = thead.getElementsByTagName("tr");
for(var i=0, limit=tr.length; i < limit; ++i )
{
 alert(tr[i].id)
}
CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008
Commented:
Not sure, but I believe this would have worked as well. Give them both a try:
var tbl = document.getElementById("myTable");
var tr = tbl.getElementsByTagName("tr");
for(var i=0, limit=tr.length; i < limit; ++i )
{
 alert(tr[i].id);
}

PS: change your id on your table to "myTable" uppercase "T" since that's what I used on the code

Author

Commented:
bravo, thanks!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.