43

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?

daGrevis
  • 21,014
  • 37
  • 100
  • 139

6 Answers6

96
var total = $('ul li').length;
$('ul li').each(function(index) {
    if (index === total - 1) {
        // this is the last one
    }
});
Luke Sneeringer
  • 9,270
  • 2
  • 35
  • 32
  • 5
    + For the good example, but this doesn't work while looping JSON object with named `keys` (`indexes`) since `index` is not a number. – Ifch0o1 Feb 18 '16 at 11:18
14
var arr = $('.someClass');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
BnW
  • 592
  • 1
  • 3
  • 13
9

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(",");
    }
});
Raynos
  • 166,823
  • 56
  • 351
  • 396
6
    var length = $( 'ul li' ).length
    $( 'ul li' ).each( function( index ) {
        if(index !== (length -1 ))
          $( this ).append( ',' );
        else
          $( this ).append( ';' );

    } );
Mutt
  • 937
  • 6
  • 9
3

It is a very old question, but there is a more elegant way to do that:

$('ul li').each(function() {
    if ($(this).is(':last-child')) {
        // Your code here
    }
})
Luca Fagioli
  • 12,722
  • 5
  • 59
  • 57
2

using jQuery .last();

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

DEMO

Marco Allori
  • 3,198
  • 33
  • 25