How to Apply Style to Last Element of List with jQuery

Last Updated on February 14, 2021 by Roshan Parihar

In this tutorial, learn how to apply style to last element of list using jQuery. The short answer is: use the jQuery :last selector that selects only the end item of the group element.

There are many other selectors that can also use to add style to the rear item that you will find in the examples given below.

How to Apply Style to the Last Element of List with jQuery :last Selector

To select the last item of the list and apply the style, you have to use the jQuery :last selector. It applies the CSS style to the last li item using jQuery. You can add CSS on button click event of jQuery as given below:

Test it Live

Output

  • First li items.
  • Second li item.
  • Third li item.
  • Forth li item.
  • Last li item.

When you click the button given above, it applies the color to the end li item of the list element.

Use jQuery :nth-last-child(1) Selector to Add Style to End Item

You can add style to the end item of the list using the jQuery :nth-last-child(1). The value 1 is the argument that is required to select the last item of the list as given below:

Test it Live

Output

  • First li items.
  • Second li item.
  • Third li item.
  • Forth li item.
  • Last li item.


You have to click the button element given above to add a style to the selected li item.

Add Style to Rear or Final Element Using jQuery :last-child Selector

In addition to above all methods, you can also use the jQuery :last-child selector that selects the rear item of the list element. It also selects and applies the style to the last item as given below:

Test it Live

Output

  • First li items.
  • Second li item.
  • Third li item.
  • Forth li item.
  • Last li item.


Click the button given above and see the last item of the list whose color changes to the specified color using jQuery.

I hope you like this tutorial on how to apply a style to the last element of the list using jQuery.

You May Also Like to Read