10

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().

3
  • 1
    even with dynamic ID's, it should still work. Commented Dec 6, 2012 at 14:52
  • 2
    table.tr[1].id -> b? Commented Dec 6, 2012 at 14:53
  • 2
    @MarcB it should be table.rows not table.tr Commented Dec 6, 2012 at 15:06

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

Comments

5

"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/

Comments

2

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>

7 Comments

Why use jQuery on something as simple as getting a table row?
Just an example to show how nth-child (also a CSS selector) works.
Fair enough, but you might want to mention how horribly slow jQuery is on things like this.
ya i know it work using jquery bt i dnt want use that.Thanks for your quick reply
Yes, jQuery is slow at this. And you dont want to load it just for there simple things.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.