Search code examples
jqueryjquery-selectors

:last vs :last-child selector


I've noticed that $( 'filter:last' ) is different from $( 'filter:last-child' ) in jQuery.

I tried the jQuery docs but had a hard time understanding what additional purpose :last serves and why they both exist.

Apparently, :last is a jQuery extension and not in the CSS specification. So, the question came to my mind of how it is different from the traditional :last-child. Also, there happens to be a .last() method in jQuery which is said to be more efficient than $( 'filter:last' ), so what use does the :last selector have?


Solution

  • They are very similar. The difference is that if you have something like

    <div>
      <p>hi</p>
      <p>bye</p>
    </div>
    <div>
      <p>hi</p>
      <p>bye</p>
    </div>
    

    $('p:last-child') will select both <p>bye</p> elements whereas $('p:last') will select only the second one. It's also true that the same thing can be done with $('p').last(), by adding :last as a selector jQuery allows for using filter with :last without having to make the argument of the filter be a function.