Home > Blockchain >  Fetching the last item of nested items with a selector
Fetching the last item of nested items with a selector

Time:05-02

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 >Simple Item</li>
  <li >Simple Item</li>
  <li >Simple Item (this one)</li>
  <li >
    <ul>
       <li >Simple Item</li>
       <li >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/

CodePudding user response:

You can use .each()

$("ul").each(function(){
  $("> li.simple:last" , this).css("color" , "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li >Simple Item</li>
  <li >Simple Item</li>
  <li >Simple Item (this one)</li>
  <li >
    <ul>
       <li >Simple Item</li>
       <li >Simple Item (this one)</li>
    </ul>
  </li>
</ul>

  • Related