Select second to last element

2020-07-13 01:43发布

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.

6条回答
Bombasti
2楼-- · 2020-07-13 01:52

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楼-- · 2020-07-13 02:01

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楼-- · 2020-07-13 02:06

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/

查看更多
太酷不给撩
5楼-- · 2020-07-13 02:07

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.

查看更多
6楼-- · 2020-07-13 02:09

You can use .prev()

$("select.x").last().prev();
查看更多
够拽才男人
7楼-- · 2020-07-13 02:09

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/

查看更多
登录 后发表回答