jQuery :last-child Selector

The jQuery :last-child selector selects all the items that are the last child of the parent element. The parent elements can be a table and list items to select the last item of them.

You can find it more clear with the examples given below. Let’s start with the syntax of the selector.

jQuery :last-child Selector

Syntax of jQuery :last-child Selector

The syntax of the jQuery :last selector is given below.

Syntax
$(“:last-child”)

You have to use the element name before the selector to select the required element.

Select Last List Item With the Selector

The selector selects all the last elements of the two list elements given below. The example contains the two ul elements and you have to select the last element of both of them.

If you want to get the perfect example for the difference between :last and :last-child. See the example below contains the two-button which you check to find the difference.

Example

Test it Live

Output

Click below buttons

  • First item of first ul
  • 2nd item
  • 3rd item
  • Last item of first ul
  • First item of second ul
  • PHP
  • HTML
  • Last item of second ul

When you click the button given above, the button ‘:last-child’ selects all the last elements of both the group element. If you click the button ‘:last’, it selects the last element of the second group element and applies the ‘yellow’ color.

jQuery :last-child Selector Select Last Row of Table

Let’s take a table element to select the last child element. When you want to select the last row of the table, you can use the below example. You can also use the jQuery :last selector to select the last element as the example given below.

The example contains the table and the button element. It also uses the jQuery click event to perform the task on button click.

Example

Test it Live

Output

Sr No Name
1 First
2 Second
3 Third
4 Forth
5 Last

You have to click the button given above to apply the background color to the last row of the table. It applies the ‘yellow’ background color when you click the button.

Difference Between :last-child and :last Selector

If there are two group elements of the same type(e.g. two ul elements), the :last-child selector select the last element of both the group elements(e.g. both first and second ul elements). It’s not the same as the :last selector as the :last selector selects the last child of only the second group element(e.g. second ul element).

I hope you like this tutorial of jQuery :last-child selector to select all end items. 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