Last element of Class

2019-09-21 18:41发布

问题:

How can I check if a element with a certain class is the last of that class?

<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div> // I want to check if this is the last element of this class
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>

回答1:

The following will loop each div and say which div is last div

var count = $('div.foo').length;

$('div.foo').each(function(index){
  if(index == (count-1))
  {
    alert("this is last div" + index);
  }
});

like this you can get last element of the class

 var last_foo_div = $('div.foo:last');

or

   var foodivs= $('div.foo');
   var lastdiv  = foodivs.last();


回答2:

As I'm not sure how you are identifying this variable, lets say $foo is a jQuery object for that particular element.

You could do:

if (!$foo.next(".foo").length){
   //its the last foo
}

Live Demo: http://jsfiddle.net/2W6eT/



回答3:

if ($('.foo').next('.foo').length == 0)
   alert("This is last Element")