Skip to content Skip to sidebar Skip to footer

Last Element Of Class

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

Solution 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();

Solution 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/

Solution 3:

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

Post a Comment for "Last Element Of Class"