[英]How to get row id from row Index in table using JavaScript
Suppose this is my table: 假设这是我的表:
<table>
<tr id="a">
<TD>a</TD>
</tr>
<tr id="b">
<TD>b</TD>
</tr>
</table>
How can I get row id using the row index from a table? 如何使用表中的行索引获取行ID?
Above is just an example where id is static but in my case my id is dynamic, so I can't use document.getElementById()
. 上面只是一个例子,其中id是静态的但在我的情况下我的id是动态的,所以我不能使用
document.getElementById()
。
Assuming you have only one table on your page: 假设您的页面上只有一个表:
document.getElementsByTagName("tr")[index].id;
Preferably though, you'd give your table
a id
, though, and get your row like this: 最好不过,你会给你的
table
一个id
,不过,让你的行这样的:
<table id="tableId">
<tr id="a">
<td>a</td>
</tr>
<tr id="b">
<td>b</td>
</tr>
</table>
var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);
This way, you can be certain you don't get any interference, if you have multiple tables in your page. 这样,如果页面中有多个表格,您可以确定不会受到任何干扰。
"So, How can i get row id using row Index from a table"
“那么,我如何使用表格中的行索引获取行ID”
You would select the table
, and use the .rows
property to get the row by index. 您将选择该
table
,并使用.rows
属性按索引获取行。
var table = document.getElementsByTagName("table")[0]; // first table
var secondRow = table.rows[1]; // second row
Then you just get the ID in the typical manner. 然后,您只需以典型方式获取ID。
console.log(secondRow.id); // "b"
DEMO: http://jsfiddle.net/MErPk/ 演示: http : //jsfiddle.net/MErPk/
Answer has been edited With CSS3 you can use the nth-child selctor. 已编辑答案使用CSS3,您可以使用nth-child selctor。 Here the example shows the rowIndex = 2
这里的例子显示了rowIndex = 2
alert(document.querySelector("table tr:nth-child(2)").id);
In jQuery you can do this with 在jQuery中,您可以使用
alert($("table tr:nth-child(2)").attr('id'));
The same syntax nth-child() can be used in CSS 可以在CSS中使用相同的语法nth-child()
<style>
tr:nth-child(2) {
color: red;
}
</style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.