开发者

Javascript - get all table -> tr > id values

开发者 https://www.devze.com 2022-12-20 11:15 出处:网络
I would like to access all the values of a table tr id field. <table> <tr id=\"1\"></tr>

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]);
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号