Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last child of each parent with jQuery

Is there an easy way to select last li of each of these lists with jQuery?

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>
<ul>
    <li>1</li>
    <li>2</li>
</ul>

I've tried those two methods but both of them return only one element.

$("ul li").last()
$("ul li:last")

I would use the CSS :last-child pseudo-class but since it was introduced in CSS3 and IE8 doesn't support it, I cannot

like image 866
Az. Avatar asked Jul 18 '13 15:07

Az.


2 Answers

I would use the CSS :last-child pseudo-class but since it was introduced in CSS3 and IE8 doesn't support it, I cannot

You can since you're using jQuery to select your elements, because jQuery implements it itself so that browsers that don't support it natively in CSS can still use it:

$("ul li:last-child")
like image 175
BoltClock Avatar answered Sep 18 '22 11:09

BoltClock


The :last-child selector is what you need. Same logic as the CSS3 :last-child selector, but you can freely use it in jQuery as jQuery will provide it for you even if the browser's CSS engine does not understand it.

$("ul li:last-child")

From the documentation:

While :last matches only a single element, :last-child can match more than one: one for each parent.

Nice little demo attached

like image 33
kapa Avatar answered Sep 19 '22 11:09

kapa