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 $(selector).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. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

$.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("Mine is " + this + ".");
       return (this != "three"); // will stop running after "three"
   });

    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 );
 });

Support and Contributions

Need help with jQuery.each() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.each()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://www.toxa.de/ Thomas

    jQuery.each() is returning what is passed in as collection in first argument, probably altered in iterator callback.

  • 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)?

  • http://bhuvidya.myopenid.com/ bhu vidya

    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

  • 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 :-)

  • http://twitter.com/bhuvidya bhu Boue vidya

    sometimes i want to break out of the $.each() function, returning that same value to calling code

    eg

    if ($.each(coll, function(idx, value) {
    if (something) {
    return 6;
    }
    }) > 3) {
    ….
    }

    maybe a dumb example, but you get the idea – it would save having to set flag vars etc

  • Anonymous

    Hi Doug,
    Like you I found this example a bit confusing. The first each() loops to four (4) like we presumed, but the second each() doesn’t acquire i @ i=5, the second each() actually runs all over again from the beginning and re-writes what the first each() did but stopping after 5 giving the false-impression that it acquired i @ 5, which it did not.

    Copy the code your self and change the 2nd each()’s “.createTextNode(” – ” + val)” to “.createTextNode(” haha different ” + val)” and you’ll see that all the example is changed and re-written by the second each.

  • Cru

    Is there a way to take the results of each() and store it elsewhere where it won’t be overwritten?
    If it were a for loop, you could make an array with [i] to store things in. I just can’t seem to think my way through this one though.

    Lets say I have XML nodes, I want to break them into arrays – each element having it’s own array, so that is array[0], is array[1] and the subelements are multidimensional: array[0][0] for ‘s child.

    The problem I have is that without an iterator [i] the array just keeps getting overwritten. Did I miss something?

  • doug

    Well, I played with it some more and my conclusion is that the line in the first .each() is not doing anything:

    return (this !== “four”); // will stop running to skip “five”

    Cut the example out into a new document, comment out the 2nd .each() altogether and you’ll see the fifth line prints regardless. I understand what’s trying to be achieved (returning false after the fourth iteration to stop a fifth) but it doesn’t actually work.

    Play around with that line, change it to return (this !== “one”); or any other number and you’ll see nothing change.

  • Anonymous

    An example of replacing a standard for loop the .each() method would be instructive.

    Before:

    for (index in collection)
    {
    var value = collection[index];
    alert(index + ‘: ‘ + value);
    }

    After:

    jQuery.each(collection, function(index, value)
    {
    alert(index + ‘: ‘ + value);
    });

  • darryl

    you can assign it to an object
    use some attribute from within the each statement as an index
    eg.
    var r = {};
    $( ‘.lookup’).each(function(){
    r[$(this).attr("id")] = ’1′ ;
    });

  • Jon

    I needed to use to use $(this) within the function(i,e) for this to work. I also added one to remove the tabindex from hyperlinks so that our customer service reps can quickly tab through fields without landing on the logo at top of the page, menu links, etc.

    $(‘a:visible’).each(function(i,e){$(this).attr(‘tabindex’, -1);});
    $(‘:input:visible’).each(function(i,e){$(this).attr(‘tabindex’, i);});

  • Dannii

    The description of .each() shown here http://api.jquery.com/category/utilities/ is wrong.
    It is the caption for the first example, rather than the description of the whole function.

  • cz

    Your example is for .each(), not jQuery.each(). Anyway, you don’t need .each() for the first line:

    $(‘a:visible’).attr(‘tabindex’, -1);

  • http://piotr.openid.dobrogost.pl/ Piotr Dobrogost

    What object does each() return?
    Not even a single word on this…

  • Anonymous

    It returns the collection object. If you pass it [1,2], it returns [1,2]. If you pass it { a: ‘thing’, b: ‘other’ }, it returns the object with those properties.

  • http://jeoftp.blogspot.com Jeoff

    One subtle problem with using “this” is that it will always come through as an “object” instead of a “string”, even if you’re iterating through strings. For example:

    var arr = [ "one", "two", "three", "four", "five" ];

    jQuery.each(obj, function(i, val) {
    typeof this === “object”;
    $(“#” + i).html(this); //does not work
    typeof val === “string”;
    $(“#” + i).html(val); //works fine
    });

  • bob

    Is it possible to use .each() to change the value of the element in the array it is iterating over?

  • http://www.learningjquery.com/ Karl Swedberg

    Sure. Here is a simple example:

    var foo = [1,2,3];
    $.each(foo, function(index, val) {
    foo[index] = val+10;
    });

  • Serge_toure

    Can i write also

    var foo = [1,2,3];
    $.each(foo, function(index, val) {
    val= val+10;
    });

  • zoorock

    thx, almost did the same error and mixed them up!

  • Rhis

    how to break the looping of each. function

  • http://www.nbsp.es Marc

    use return false

  • Nkammermann

    Is there a way to find out when the last loop is in .each ?

    I'll do some post requests within the each, and need to wait till last item post hast finished
    so i can update the page.

    $('.someClass').each(function(i) {
    var someObj = new Object();
    someObj['data'] = i;

    $.post('query.php',someObj,function(data) {
    if(data == 'OK' && IS_LAST_ITEM) {
    window.location = '/nextpage';
    }
    }

    because otherwise it does not execute more than one post .. so at the moment i'm not able to do an automated forward ..any ideas?

  • Exelian

    It's not altered by the callback. Instead the return from the callback is used to determine whether an element should be skipped or not.

  • RCWatson

    This is a great tutorial and I'd love to use the techniques described, but my reading of the CC no-derivatives license on it seems to make the article of little use in developing software I might distribute to others in the future. Could you clarify?

  • Mrgreenfur

    This runs through each item and isn't suitable for returning a value part-way through. To return values part way, use a traditional for loop.

  • http://twitter.com/ahmedkuzza Asep Ahmad

    Hi, I need help… I want to place different background icon on H2 elements in my project using .each() code but it didn't work. This my code :

    var map = ["image1.png","image2.png","image3.png","image4.png"];
    $(“H2″).each(map,function(index,value){
    $(this).css(“background”,value);
    })

  • http://blog.zanematthew.com/ Zanematthew

    Is it possible to pass in a reference to another object? Such as

    // this does not work
    .each(a.b, function())

    where data is an object of objects? currently I'm assigning it then passing it in directly like the following:

    // this works
    data = a.b
    .each(data, function())

  • http://twitter.com/mesh Mike Chambers

    Is there any advantage to using jquery in this case? Any performance benifits from using jQuery.each over a simple for loop?

  • http://justkidding.com tqwhite

    First, the reason I came to add a note is this: if you use $.each() to iterate over an array that has had an element (other than the last one) removed, ie, delete(item[x]), it will crash with a message “item is null” because of the missing index number.

    Second, you can break out of a $.each() loop by returning false from the function.

    Third, you can change the object over which you are iterating by just changing the item that is passed in. Since the item is passed by reference, the change is permanent.

    Fourth, you can pass elements out of the each with closure. Simply create a variable in the scope immediately outside the loop and add the elements you want to it inside the loop function.

  • http://justkidding.com tqwhite

    First, the reason I came to add a note is this: if you use $.each() to iterate over an array that has had an element (other than the last one) removed, ie, delete(item[x]), it will crash with a message “item is null” because of the missing index number.

    Second, you can break out of a $.each() loop by returning false from the function.

    Third, you can change the object over which you are iterating by just changing the item that is passed in. Since the item is passed by reference, the change is permanent.

    Fourth, you can pass elements out of the each with closure. Simply create a variable in the scope immediately outside the loop and add the elements you want to it inside the loop function.

  • RedYeti

    I can't find an answer to that in the above API doc but from memory of reading the relevant section of a book on JQuery: The advantage is that you don't need to guard calls with “hasOwnProperty” (as you should do with “for each”: http://sweatte.wordpress.com/j… ).

    However, I also recall that it's not necessarily as fast as “for each” – I'd like to hear from someone else on that myself!

  • http://justkidding.com tqwhite

    First, the reason I came to add a note is this: if you use $.each() to iterate over an array that has had an element (other than the last one) removed, ie, delete(item[x]), it will crash with a message “item is null” because of the missing index number.

    Second, you can break out of a $.each() loop by returning false from the function.

    Third, you can change the object over which you are iterating by just changing the item that is passed in. Since the item is passed by reference, the change is permanent.

    Fourth, you can pass elements out of the each with closure. Simply create a variable in the scope immediately outside the loop and add the elements you want to it inside the loop function.

  • RedYeti

    I can't find an answer to that in the above API doc but from memory of reading the relevant section of a book on JQuery: The advantage is that you don't need to guard calls with “hasOwnProperty” (as you should do with “for each”: http://sweatte.wordpress.com/j… ).

    However, I also recall that it's not necessarily as fast as “for each” – I'd like to hear from someone else on that myself!

  • ahui

    This a simple example:
    var tt = $.each( ['a','b','c'], function(i, l){
    //alert( “Index #” + i + “: ” + l );
    });
    $.each( tt, function(i, l){
    alert( “Index #” + i + “: ” + l );
    });

  • Michael Courcy

    (function($){
    $.fn.myFonc(data){
    return this.each(function (i) {
    //do something with this and data
    alert(this.id + “_” data.message)
    }
    }
    })(JQuery);

    //use it
    $('#product-data input[type=text]“).myFonc({message:”foo”});

  • Leon Chen

    Is there any advantage to use (index, element) as the parameters order instead of (element, index)? Seems most times I care the element more than the index/key. If it is (element, index), then the callback could just be: function (v) {…}.
    jQuery.map() and jQuery.grep() use the order of (element, index).

  • Nagaharish Movva

    Here this one more post about break and continue in Jquery loops (functions)
    http://shareourideas.com/2010/10/18/break-and-continue-in-jquery-each-function/

  • Constantine

    i want to mix .each and $.each example
    $(“<select>”).each( {a:1,b:2,c:3}, function(i,e){ $(this).append($(“<option>”).val(i).text(e)) })</option></select>

  • Vijay Allagi

    I dont want to print the first element in $.each(). Is there anyway how can i do it.I am very new to jquery

  • Slagheap

    If you mean you want to skip the first item in the .each() and move on to the rest…

    var myArray=["skipThis", "dothis", "andThis"];
    $.each(myArray, function(index, value) {
    if (index == 0) {
    return true; // equivalent to 'continue' with a normal for loop
    }
    // else do stuff…
    alert (index + “: ” value);
    });

    Should print:
    1: doThis
    2: andThis

  • BigDave2011

    i have a var i cant seem to get values from i wonder if anyone can help as i cant change the way the array displays
    var jabber_resources = [ {name:'DavesBaby', priority:5, show:'available', long_show:'available', status:'' }];

    if someone could give an example that would be grat

  • Nicolas Clavaud

    You may to use first callback param (index) and compare it to your array's length:

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