Select second to last element

2020-07-13 01:57发布

问题:

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.

回答1:

You can use .prev()

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


回答2:

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.



回答3:

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


回答4:

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/



回答5:

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/



回答6:

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.