Joe
Joe

Reputation: 1645

finding the <tr> in a table

I have a table:

<table id="Table">
    <tr id="tr-1">
        <td>1</td>
    </tr>
    <tr id="tr-2">
        <td>2</td>
    </tr>
    <tr id="tr-3">
        <td>3</td>
    </tr>
    <tr id="tr-4>
        <td>4</td>
    </tr>
    <tr id="tr-5">
        <td>5</td>
    </tr>
</table

I have code that looks for the last <tr> in that table

var ID = $("#Table tr:last").attr("id");

Now I want to find the id of the <tr> that is two <tr>'s back from the ID that I collected. The answer would be <tr> id="3". But what code would I write to get that answer?

Upvotes: 2

Views: 196

Answers (3)

Rob W
Rob W

Reputation: 349252

Use the :nth-last-child selector: http://jsfiddle.net/7QFDB/.

var ID = $("#Table tr:nth-last-child(2)").attr("id");

This selector is implemented in most modern browsers. For compatibility, this jQuery plugin can be used.

Upvotes: 5

charlietfl
charlietfl

Reputation: 171698

Can get the index() of last row then use that to go any number of rows you want

   var lastRowIndex=  $("#Table tr:last").index();
   var different_row=  $("#Table tr").eq(lastRowIndex-2) 

Upvotes: 1

Diego
Diego

Reputation: 18379

You can use prev() twice:

var id = $("#Table tr:last").prev().prev().attr("id");

Upvotes: 1

Related Questions