jQuery :nth-last-child() Selector

The jQuery :nth-last-child() selector selects all the child elements that are the nth-child of their parents. It selects the elements by specifying the position which is counted from the last child.

jQuery nth-last-child Selector image

Syntax of jQuery :nth-last-child() Selector

The syntax of jQuery :nth-last-child() selector is given below.

Syntax
$(“:nth-last-child(number|even|odd|equation)”)

To select the element, you have to specify the tag name. The tag name decides to select the child of the exact group element

It takes an argument which is the position of the child for the specified parent. The position can be a number, even and odd element, and an equation that decides the position. See the description of the arguments to pass to the selector.

Description of Parameters

Parameter Name Description
number Specify the position of the element to select. A position for group element starts from 1.
even Select the even elements of the group elements like table and list.
odd You can select the odd items of the group elements like table and list.
equation An equation is a formula derived from an+b to select the elements. For example, if you specify 2n, it selects all elements present in the position 0, 2, 4, 6,…n. It’s easy to solve the equation by putting the value of n as 0,1,2,…n.

jQuery :nth-last-child Selector Select Specified Table Row

If you want to select the exact child element, you have to specify the position of the element starting from 1. However, the selector counts the position from the end child element.

Let’s make it more clear with the example given below. The example contains the table with six rows. If you specify 2 as the argument value, the selector counts from the end row as 1, 2.., etc, and select the second last row.

Example

Test it Live

Output

Sr No Name
1 RAM
2 Hard Disk
3 External Drive
4 DVD Drive
5 Memory Card

When you click the button in the example given above, it selects the second last row of the table. It applies the background color as ‘yellow’ to highlight the selected row.

Select Specified List Element With the Selector

The same reverse counting will be applied to the list element. If you specify the argument as 2 to select the child of the list element. It selects the second last list items as given in the example below.

Example

Test it Live

Output

  • Email Marketing
  • Affiliate Marketing
  • Social Sharing
  • Digital Marketing
  • Promotion

You have to click the button given in the example above to select the element. When you click the button, it selects the 4th list item and apply the red color to the text.

I hope you like this tutorial of jQuery :nth-last child selector to select all elements counted from the end. If you have any queries regarding the tutorial, please comment below.

Also tell me, what other methods you are using with the selector by commenting below.

References