jQuery Selectors Last and Last-Child

jQuery has a plethora of selectors, two of which being :last and :last-child. It should be very obvious that these do not achieve the same goal. Well, I spent the better part of an hour figuring that out. I went down the page of selectors knowing jQuery has a selector for :last-child, and saw :last first. I toyed around with it a bit to no avail. I finally did a couple searches on jQuery last selectors and found out that jQuery also has a :last-child selector, which is what I was really looking for.

The :last selector selects the last element on the page matching the entire selector. The :last-child selector selects all last children matching the entire selector.

$(‘div p:last’) would select the paragraph highlighted in red:

<div>
    <p>Paragraph</p>
    <p>Paragraph</p>
    <p>Paragraph</p>
</div>
<div>
    <p>Paragraph</p>
    <p>Paragraph</p>
    <p>Paragraph</p>
</div>
<div>
    <p>Paragraph</p>
    <p>Paragraph</p>
    <p>Paragraph</p>
</div>

while $(‘div p:last-child’) would select the paragraphs highlighted in red:
<div>
    <p>Paragraph</p>
    <p>Paragraph</p>
    <p>Paragraph</p>
</div>
<div>
    <p>Paragraph</p>
    <p>Paragraph</p>
    <p>Paragraph</p>
</div>
<div>
    <p>Paragraph</p>
    <p>Paragraph</p>
    <p>Paragraph</p>
</div>

3 comments

  1. You can also specify a context with your selector, which would have enabled you to use p:last. Kind of confusing, but it works:

    $(‘p:last’, ‘div’)

  2. Thanks for the example, been searching for more info regarding the :last selector, considering that the jquery api did not offered enough info.

Comments are closed.