Reputation: 65
I thought this should be pretty easy, but I can't seem to figure it out! I'm trying get the last item with a class of .simple
in each parent.
<ul>
<li class="simple">Simple Item</li>
<li class="simple">Simple Item</li>
<li class="simple">Simple Item (this one)</li>
<li class="group">
<ul>
<li class="simple">Simple Item</li>
<li class="simple">Simple Item (this one)</li>
</ul>
</li>
</ul>
I tried with :last
$('ul > li.simple:last').css('color', 'red');
But it fetches the very last item that matches.
How can I fetch each last .simple
?
Here's a fiddle:
http://jsfiddle.net/hav497t1/48/
Upvotes: 1
Views: 41
Reputation: 24001
You can use .each()
$("ul").each(function(){
$("> li.simple" , this).last().css("color" , "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="simple">Simple Item</li>
<li class="simple">Simple Item</li>
<li class="simple">Simple Item (this one)</li>
<li class="group">
<ul>
<li class="simple">Simple Item</li>
<li class="simple">Simple Item (this one)</li>
</ul>
</li>
</ul>
As @cheesyman mentioned in the comment below
As of jQuery 3.4, the :last pseudo-class is deprecated. Remove it from your selectors and filter the results later using .last().
Upvotes: 1