daGrevis
daGrevis

Reputation: 21333

How to Find Out Last Index of each() in jQuery?

I have something like this...

$( 'ul li' ).each( function( index ) {

  $( this ).append( ',' );

} );

I need to know what index will be for last element, so I can do like this...

if ( index !== lastIndex ) {

  $( this ).append( ',' );

} else {

  $( this ).append( ';' );

}

Any ideas, guys?

Upvotes: 43

Views: 90916

Answers (6)

Luca Fagioli
Luca Fagioli

Reputation: 13349

Here is another way to do that:

$('ul li').each(function() {
    if ($(this).is(':last-child')) {
        // Your code here
    }
})

Upvotes: 4

Marco Allori
Marco Allori

Reputation: 3294

using jQuery .last();

$("a").each(function(i){
  if( $("a").last().index() == i)
    alert("finish");
})

DEMO

Upvotes: 3

BnW
BnW

Reputation: 602

var arr = $('.someClass');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});

Upvotes: 14

Luke Sneeringer
Luke Sneeringer

Reputation: 9428

var total = $('ul li').length;
$('ul li').each(function(index) {
    if (index === total - 1) {
        // this is the last one
    }
});

Upvotes: 98

Raynos
Raynos

Reputation: 169383

Remember to cache the selector $("ul li") because it's not cheap.

Caching the length itself is a micro optimisation though, that's optional.

var lis = $("ul li"),
    len = lis.length;

lis.each(function(i) {
    if (i === len - 1) {
        $(this).append(";");
    } else {
        $(this).append(",");
    }
});

Upvotes: 9

Mutt
Mutt

Reputation: 935

    var length = $( 'ul li' ).length
    $( 'ul li' ).each( function( index ) {
        if(index !== (length -1 ))
          $( this ).append( ',' );
        else
          $( this ).append( ';' );

    } );

Upvotes: 6

Related Questions