tags:

views:

373

answers:

2

I would like to access all the values of a table tr id field.

<table>
<tr id="1"></tr>
<tr id="2"></tr>
<tr id="3"></tr>
<tr id="4"></tr>
<tr id="5"></tr>
</table>

What I would like to do is, using a javascript function, get an array and have acess to

[1,2,3,4,5]

Thank you very much!

+5  A: 
var idArr = [];

var trs = document.getElementsByTagName("tr");

for(var i=0;i<trs.length;i++)
{
   idArr.push(trs[i].id);
}
zincorp
Nice, but right before the second line I would var `table = document.getElementById("tableId");` then change the second line to `table.getElementsByTagName("tr");`. +1
karim79
That's is a good point if he needs to obtain the rows for a specific table
zincorp
A: 

Please keep in mind that HTML ids must start with an alphanumeric character in order to validate, and getElementsByTagName returns a collection, not an array. If what you really want is an array of all your table rows, there's no need to assign an ID to each. Try something like this:

<table id="myTable">
<tr><td>foo</td></tr>
<tr><td>bar</td></tr>
<tr><td>baz</td></tr>
</table>

var i, tr, temp;

tr = [];
temp = document.getElementById('myTable').getElementsByTagName('TR');
for (i in temp) {
   if (temp[i].hasOwnProperty) {
      tr.push(temp[i]);
   }
}
Kent Brewster