lovespring
lovespring

Reputation: 19589

How to select last child element in jQuery?

How to select last child element in jQuery?

Just the last child, not its descendants.

Upvotes: 114

Views: 191756

Answers (6)

Christophe Roussy
Christophe Roussy

Reputation: 17049

For 2019 ...

jQuery 3.4.0 is deprecating :first, :last, :eq, :even, :odd, :lt, :gt, and :nth. When we remove Sizzle, we’ll replace it with a small wrapper around querySelectorAll, and it would be almost impossible to reimplement these selectors without a larger selector engine.

We think this trade-off is worth it. Keep in mind we will still support the positional methods, such as .first, .last, and .eq. Anything you can do with positional selectors, you can do with positional methods instead. They perform better anyway.

https://blog.jquery.com/2019/04/10/jquery-3-4-0-released/

So you should be now be using .first(), .last() instead (or no jQuery).

Upvotes: 3

subindas pm
subindas pm

Reputation: 2784

Hi all Please try this property

$( "p span" ).last().addClass( "highlight" );

Thanks

Upvotes: 2

Yoram de Langen
Yoram de Langen

Reputation: 5509

You can also do this:

<ul id="example">
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
</ul>

// possibility 1
$('#example li:last').val();
// possibility 2
$('#example').children().last()
// possibility 3
$('#example li:last-child').val();

:last

.children().last()

:last-child

Upvotes: 164

Philip
Philip

Reputation: 7166

For perfomance:

$('#example').children().last()

or if you want a last children with a certain class as commented above.

$('#example').children('.test').last()

or a specific child element with a specific class

$('#example').children('li.test').last()

Upvotes: 67

ScottyG
ScottyG

Reputation: 3420

If you want to select the last child and need to be specific on the element type you can use the selector last-of-type

Here is an example:

$("div p:last-of-type").css("border", "3px solid red");
$("div span:last-of-type").css("border", "3px solid red");

<div id="example">
            <p>This is paragraph 1</p>
            <p>This is paragraph 2</p>
            <span>This is paragraph 3</span>
            <span>This is paragraph 4</span>
            <p>This is paragraph 5</p>
        </div>

In the example above both Paragraph 4 and Paragraph 5 will have a red border since Paragraph 5 is the last element of "p" type in the div and Paragraph 4 is the last "span" in the div.

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101614

By using the :last-child selector?

Do you have a specific scenario in mind you need assistance with?

Upvotes: 8

Related Questions