Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Above is just an example where id is static but in my case my id is dynamic, so I can't use document.getElementById().

like image 959
Prateek Avatar asked Dec 06 '12 14:12

Prateek


3 Answers

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="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.

like image 56
Cerbrus Avatar answered Oct 08 '22 13:10

Cerbrus


"So, How can i get row id using row Index from a table"

You would select the table, and use the .rows property to get the row by index.

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.

console.log(secondRow.id); // "b"

DEMO: http://jsfiddle.net/MErPk/

like image 34
I Hate Lazy Avatar answered Oct 08 '22 13:10

I Hate Lazy


Answer has been edited With CSS3 you can use the nth-child selctor. Here the example shows the rowIndex = 2

 alert(document.querySelector("table tr:nth-child(2)").id);

In jQuery you can do this with

 alert($("table tr:nth-child(2)").attr('id'));

The same syntax nth-child() can be used in CSS

<style>
    tr:nth-child(2) {
        color: red;
    }
</style>
like image 33
Eystein Bye Avatar answered Oct 08 '22 12:10

Eystein Bye