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

daGrevis picture daGrevis · May 19, 2011 · Viewed 77.2k times · Source

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?

Answer

Luke Sneeringer picture Luke Sneeringer · May 19, 2011
var total = $('ul li').length;
$('ul li').each(function(index) {
    if (index === total - 1) {
        // this is the last one
    }
});