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

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


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


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


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(",");    }});