jqueryloopsindexingeach

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?


Solution

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