Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
daGrevis Avatar asked May 19 '11 16:05

daGrevis


People also ask

How do I find the last index?

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .

How to get the last index in javascript?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

Is last in jQuery?

The last() function is an inbuilt function in jQuery which is used to find the last element of the specified elements.


2 Answers

var total = $('ul li').length; $('ul li').each(function(index) {     if (index === total - 1) {         // this is the last one     } }); 
like image 152
Luke Sneeringer Avatar answered Sep 17 '22 12:09

Luke Sneeringer


var arr = $('.someClass'); arr.each(function(index, item) { var is_last_item = (index == (arr.length - 1)); }); 
like image 33
BnW Avatar answered Sep 16 '22 12:09

BnW