jQuery: Get the last child element with one line of jQuery code

By | May 29, 2021

Hello Everyone, I’m back with another blog post which is related to jQuery library. Today, I am going to share with you multiple tricks that will help you to get the last child element with one line of jQuery code.

Lets say, you have structured your HTML as following.

<ul id="example">
    <li>jQuery</li>
    <li>JavaScript</li>
    <li>NodeJs</li>
    <li>ReactJs</li>
</ul>

And, you might want to add a specific class (in my case I’m going to add .active class) to the last child of element. To do that, there are multiple methods are available and I’m going to cover some of them.

Get the last child element using :last selector

The :last selector is used to select the last child.

$(function() {
   $('#example li:last').addClass("active");
});

Select the last child with :last-child selector

The :last-child selector, help us in getting all those elements which are last child of their parent element.

$(function() {
  $('#example li:last-child').addClass("active");
});

Get the last child element using last() method

You can also use last() method which is very good performance wise. I would recommend using this method.

$(function() {
   $('#example').children().last().addClass("active");
});

Output