Belsen
Belsen

Reputation: 323

Select second to last element

i need to select the value of second to last input selectable element:

<tr><td><select class="x">...</select></td></tr>
<tr><td><select class="x">...</select></td></tr>
<tr><td><select class="x">...</select></td></tr>

The select input tag are inside tr tags.

If I use $("select.x").last(), jQuery select the last element. I need to select second to last.

Upvotes: 13

Views: 24826

Answers (6)

Anubhav Chaudhary
Anubhav Chaudhary

Reputation: 133

You need to use "nth-last-child(2)" of jquery, this selects the second last element.

You can check this here:

https://api.jquery.com/nth-last-child-selector/

Upvotes: 2

Gras Double
Gras Double

Reputation: 16373

You can use .eq() with negative indexes:

$("select.x").eq(-2);


These negative indexes are "1-indexed": -1 gives the last element, -2 the penultimate, and so on.

Upvotes: 17

Belsen
Belsen

Reputation: 323

The solutions with .prev() or nth-last-child() don't works.

<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>
<tr><td><a>...</a><select class="x"></select><a>...</a><td><tr>

The problem is the last().prev() functions return the the object <a> which i suppouse come first the select one.

The nth-last-of-type(2) selector instead return an empty object.

Upvotes: 1

Christoph
Christoph

Reputation: 51191

All of the below will do the trick (select the second last element):

$("select.x").eq(select.length - 1)

$("select.x:nth-last-of-type(2)")

$("select.x:nth-last-child(2)")

$("select.x").last().prev()

Upvotes: 7

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can use :last selector and move to the preceding element using prev:

$("select.x:last").prev();

Ref:

Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

Sample demo: http://jsfiddle.net/IrvinDominin/ck8XP/

Upvotes: 4

Anton
Anton

Reputation: 32581

You can use .prev()

$("select.x").last().prev();

Upvotes: 13

Related Questions