Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 325
Belsen Avatar asked Mar 24 '14 09:03

Belsen


People also ask

How would you access the 2nd to last element in an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.

How do I select the second last element in Dom?

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

How do you choose the last element?

The :last selector selects the last element. Note: This selector can only select one single element. Use the :last-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the last element in a group (like in the example above).


2 Answers

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/

like image 144
Anubhav Chaudhary Avatar answered Sep 23 '22 21:09

Anubhav Chaudhary


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.

like image 45
Belsen Avatar answered Sep 24 '22 21:09

Belsen