There are two Type 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. In First case : (each() function with a Selector) We can use each() as a Selector. Assume we have a simple list:
  • Item
  • Item
  • Item
Then with each() we can ask jQuery to look for all the
  • 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
  • and appends a dash and an iteration value. The resultant output is:
    • Item- 0
    • Item- 1
    • Item- 2
    In Second Case : (each() function with Array) 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 myBooks = new Array( "C Language", "C++ 7rd Edition", "Java Book", "C# DotNet", "SQL Server 2012", "AngularJS", "Windows Phone Book", "My Best Book"); We could loop around this with $.each() as follows: $.each(dickensBooks, function(i, val){ console.log("Index: " + i); console.log("Value: " + val); }); And the Output is : 0 : C Language 1 : C++ 7rd Edition 2 : Java Book 3 : C# DotNet 4 : SQL Server 2012 5 : AngularJS 6 : Windows Phone Book 7 : My Best Book We can also use Javascript objects here - Javascript Object having there name : value notation.