Select second to last element

眉间皱痕 提交于 2019-12-12 12:07:07

问题


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.



来源:https://stackoverflow.com/questions/22605785/select-second-to-last-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!