There are two flavours of each(). It can be used as selector to grab 'each' instance of a selector or it can be used to loop around objects like arrays.

Usage 1: Looping Elements in the HTML

We can use each() as a Selector. Assume we have a simple list:

<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>

Then with each() we can ask jQuery to look for all the <li> elements. Now you could of course just do that with $("li") but each allows you to keep a count of where you are.

	
 $("li").each(function(i){
	$(this).append("- " + i);
});

The above targets each <li> and appends a dash and an iteration value. The resultant output is:

<ul>
<li>Item- 0</li>
<li>Item- 1</li>
<li>Item- 2</li>
</ul>

Usage 2: Arrays

Here we will use the 'global' version of each(). Instead of reference a jQuery object first we call each() as $.each() (like $.getJSON). The global version of each takes an object such as an array as its first parameter and then a callback function as its second. The callback function is often an anonymous / inline function for code brevity. So assume we have an array as follows:

var dickensBooks=new Array(
	"The Adventures of Oliver Twist",
	"The Life and Adventures of Nicholas Nickleby",
	"The Old Curiosity Shop",
	"A Christmas Carol",
	"David Copperfield",
	"Bleak House",
	"A Tale of Two Cities",
	"Great Expectations");

We could loop around this with $.each() as follows:

	$.each(dickensBooks, function(i, val){
		
		console.log("Index: " + i);
		console.log("Value: " + val);
		
	});

What the Dickens? The $.each() first parameter is the array. Then we have the callback function placed anonymously / inline. It takes two parameter I have called 'i' and 'val'. The 'i' parameter will be equal to the index of our array - starting at zero. The 'val' parameter will be the value in that slot of the array.

We can also use Javascript objects here - Javascript Object having there name : value notation. Here is a Javascript Object:

	var dickensNovels = new Object();
	dickensNovels.title = "The Adventures of Oliver Twist";
	dickensNovels.published = 1837;
	dickensNovels.leadCharacter = "Oliver Twist";
	dickensNovels.film = "David Lean, 1948";
	dickensNovels.musical = "London, 1960"

A Javascript Object is basically an associate array. Therefore we can feed this to the $.each() lion as follows:

	$.each(dickensNovels, function(name, val){
		
		console.log("Name: " + name);
		console.log("Value: " + val);
		
	});

Please Sir, I want some more (explanation). We feed the 'dickensNovel' object into $.each() as its first parameter. Next along comes the inline function that takes two parameter that I have chosen to call 'name' and 'value' (call them what you will Sir). We can then loop away and extract all the goodies.

Take a look at the demo.

This particular usage of each() is often used in conjunction with data retrieved via JSON.

Leave a Comment