I would like to access all the values of a table tr id field.
<table>
<tr id="1"></tr>
<tr id="2"></tr>
开发者_如何学JAVA<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!
var idArr = [];
var trs = document.getElementsByTagName("tr");
for(var i=0;i<trs.length;i++)
{
idArr.push(trs[i].id);
}
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]);
}
}
精彩评论