each

jquery each last iteration

Posted on: June 22nd, 2013 by taff No Comments

 

Rainer Sturm  / pixelio.de

Rainer Sturm / pixelio.de

I occasionally need to add some extra markup when looping through elements using jQuery each. The following is an example of some Javascript which I used to parse XML data that I received from an AJAX call. To cut down on overhead I don't use jquery .size() but prefered to use the "standard" .length property.

Get the last iteration of an each loop

The idea is simple to get the last iteration in the each loop, we simply find out how many elements we have in our array, loop through them, add one to our "counting" variable or incremental and check to see if we have reached the value of .length.

The example looks like this:

//get the length of our array
var totalLen = $(this).find('filename').length;

var tmpLen = 0;

$(this).find('filename').each(function(){
//add one each time the function is called
tmpLen++;
//add the content of our filename node
str += $(this).text();
//if it's the last element add a full stop, otherwse add a comma.
if(tmpLen<=totalLen){
str += ".";
}else{
str += ", ";
}
});