jQuery API

jQuery.each()

jQuery.each( collection, callback(indexInArray, valueOfElement) ) Returns: Object

Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

  • version added: 1.0jQuery.each( collection, callback(indexInArray, valueOfElement) )

    collectionThe object or array to iterate over.

    callback(indexInArray, valueOfElement)The function that will be executed on every object.

The $.each() function is not the same as .each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

$.each([52, 97], function(index, value) { 
  alert(index + ': ' + value); 
});

This produces two messages:

0: 52
1: 97

If a map is used as the collection, the callback is passed a key-value pair each time:

var map = { 
  'flammable': 'inflammable', 
  'duh': 'no duh' 
}; 
$.each(map, function(key, value) { 
  alert(key + ': ' + value); 
});

Once again, this produces two messages:

flammable: inflammable
duh: no duh

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Examples:

Example: Iterates through the array displaying each number as both a word and numeral

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  div#five { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div id="one"></div>
  <div id="two"></div>

  <div id="three"></div>
  <div id="four"></div>
  <div id="five"></div>
<script>
    var arr = [ "one", "two", "three", "four", "five" ];
    var obj = { one:1, two:2, three:3, four:4, five:5 };

    jQuery.each(arr, function() {
      $("#" + this).text("My id is " + this + ".");
      return (this !== "four"); // will stop running to skip "five"

    });

    jQuery.each(obj, function(i, val) {
      $("#" + i).append(document.createTextNode(" - " + val));
    });
</script>
</body>
</html>

Demo:

Example: Iterates over items in an array, accessing both the current item and its index.

$.each( ['a','b','c'], function(i, l){
   alert( "Index #" + i + ": " + l );
 });

Example: Iterates over the properties in an object, accessing both the current item and its key.

$.each( { name: "John", lang: "JS" }, function(k, v){
   alert( "Key: " + k + ", Value: " + v );
 });

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for jQuery.each() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • The link under "The $.each() function is not the same as .each()" is broken above...I figured out on my own that the correct URI for that link is:

    http://api.jquery.com/each/

    See how smart I am? :D
  • i think it would be handy if the description of this method contained an explicit description of what the 'this' object is in each of its variations

    yes, it can be worked out by coding a small example but sometimes its good just to know straight away
  • doug
    In the first example, since the return is stopping the loop after "four", how does "My Id is five" end up getting displayed (as seen in red)?
  • TeMc
    It's not being displayed in reality. This demo isn't like the other demo's on jquery.com and isn't actually generated by jQuery.

    The demo you refer to is staticly HTML to visualise that the fifth item in the array does not get displayed on the page (using the color red as a reminder of it not actually being visible)

    I agree it might be confusing, but it can also be considered handy. I don't care if it stays or not. But I hope this will answer your question :-)
  • jQuery.each() is returning what is passed in as collection in first argument, probably altered in iterator callback.
  • sim
    The article is good and there is a small detail that I find a bit confusing: the example of iterating through an array uses 'key' as the first parameter name of the callback function whereas the other, iterating through an object, uses 'index' although the description says they mean just the opposite.
  • sorry, that was my mistake in the examples. fixed now.