简体   繁体   中英

Check if <li> is last in ul that has specific class

I have a list like

<ul>
  <li class="tool"></li>
  <li class="tool"></li>
  <li class="tool"></li>
  <li class="tool"></li>
  <li class="example"></li>
</ul>

I am trying to check for something like $('li').is('.tool:last') to see if certain list is last in list, where I need to ignore .example one, hence can't really use :last-child here, but for some reason I am not getting a desired result. How can I check if list is last in the list that has class .tool ?

You can get the last tool element and then check whether it is last-child or not:

var istoollastchild = $('li.tool:last').is(':last-child');

Working Demo

$('li.tool').is(':last-child');

You could filter it, eg:

var $lastLIsTool = $('ul li.tool').filter(function(){
    return !$(this).nextAll('li.tool').length
});

-DEMO-

You can use

 if (selected_object.is(current_object)) {
   ...    
}

Use this code It will help you

<ul>
  <li class="tool">Not Last</li>
  <li class="tool">Not Last</li>
  <li class="tool"> Not Last</li>
  <li class="tool">Last</li>
  <li class="example">Not Last</li>
</ul>

<script>
    var lastLiWithTool = $('li.tool:last');
    $('li').click(function(){
        if ($(this).is(lastLiWithTool)) {
          alert("last li with tool");   
        }else{
        alert("not last li with tool"); 
        }
    })
</script>

DEMO: http://jsfiddle.net/8v10rx9u/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM