How to select last child element in jQuery?

2020-01-23 07:09发布

How to select last child element in jQuery?

Just the last child, not its descendants.

6条回答
叼着烟拽天下
2楼-- · 2020-01-23 07:35

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

查看更多
对你真心纯属浪费
3楼-- · 2020-01-23 07:37

By using the :last-child selector?

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

查看更多
走好不送
4楼-- · 2020-01-23 07:40

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()
查看更多
Ridiculous、
5楼-- · 2020-01-23 07:55

Hi all Please try this property

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

Thanks

查看更多
Fickle 薄情
6楼-- · 2020-01-23 07:55

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).

查看更多
smile是对你的礼貌
7楼-- · 2020-01-23 07:59

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.

查看更多
登录 后发表回答