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
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With