Javascript - 获取所有表 -> tr > id 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2268618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:32:34  来源:igfitidea点击:

Javascript - get all table -> tr > id values

javascriptdom

提问by Miguel

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

我想访问表 tr id 字段的所有值。

<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

我想做的是,使用 javascript 函数,获取一个数组并访问

[1,2,3,4,5]

Thank you very much!

非常感谢!

回答by zincorp

var idArr = [];

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

for(var i=0;i<trs.length;i++)
{
   idArr.push(trs[i].id);
}

回答by Kent Brewster

Please keep in mind that HTML ids must start with an alphanumeric character in order to validate, and getElementsByTagNamereturns 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:

请记住,HTML id 必须以字母数字字符开头才能进行验证,并getElementsByTagName返回一个集合,而不是一个数组。如果您真正想要的是所有表行的数组,则无需为每个行分配 ID。尝试这样的事情:

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