jQuery API

.each()

.each( function(index, Element) ) Returns: jQuery

Description: Iterate over a jQuery object, executing a function for each matched element.

  • version added: 1.0.each( function(index, Element) )

    function(index, Element)A function to execute for each matched element.

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Suppose we had a simple unordered list on the page:

<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
  

We can select the list items and iterate across them:

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
});
  

A message is thus alerted for each item in the list:

0: foo
1: bar

We can stop the loop from within the callback function by returning false.

Examples:

Example: Iterates over three divs and sets their color property.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; text-align:center; cursor:pointer; 
        font-weight:bolder; width:300px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>Click here</div>
  <div>to iterate through</div>
  <div>these divs.</div>
<script>
    $(document.body).click(function () {
      $("div").each(function (i) {
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });
</script>

</body>
</html>

Demo:

Example: If you want to have the jQuery object instead of the regular DOM element, use the $(this) function, for example:

<!DOCTYPE html>
<html>
<head>
  <style>
  ul { font-size:18px; margin:0; }
  span { color:blue; text-decoration:underline; cursor:pointer; }
  .example { font-style:italic; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  To do list: <span>(click here to change)</span>
  <ul>
    <li>Eat</li>
    <li>Sleep</li>

    <li>Be merry</li>
  </ul>
<script>
    $("span").click(function () {
      $("li").each(function(){
        $(this).toggleClass("example");
      });
    });

</script>

</body>
</html>

Demo:

Example: You can use 'return' to break out of each() loops early.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { width:40px; height:40px; margin:5px; float:left;
        border:2px blue solid; text-align:center; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button>Change colors</button> 
  <span></span>
  <div></div>
  <div></div>

  <div></div>
  <div></div>
  <div id="stop">Stop here</div>
  <div></div>

  <div></div>
  <div></div>
<script>
    $("button").click(function () {
      $("div").each(function (index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow"); 
        if ($(this).is("#stop")) {
          $("span").text("Stopped at div index #" + index);
          return false;
        }
      });
    });

</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .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 .each()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Anonymous

    What does the second callback parameter do? If the callback is fired in the context of the current DOM element, then what is the purpose of the Element parameter for the callback? This is nowhere explained.

  • http://twitter.com/cyberer cyberer

    does “continue” or “break” work?

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

      No, they don’t work here, because each() is not the same as a for loop. each() executes a callback function for each iteration, so you can return true to “continue” or return false to “break.”

      As noted above, “We can stop the loop from within the callback function by returning false.”

  • Brian Scott

    Is there a callback function that can be used to execute another function after the each() has finished?

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

      There is no need for a callback function. Any function that is placed after .each() will be executed after it.
      $(‘p’).each(function() {
      // do something with paragraphs.
      });
      $(‘p’).fadeOut(); // executes after .each() has finished

  • Anonymous

    anyway to call a particular object in a collection directly? like: $(“div”).item(3) ??

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

      $(“div”)[3] worked for me

    • Michael van Engelshoven

      Hey! If you want to get the DOM-Element, you can use the .get() function:
      $(“div”).get(3)

      The elements in your jQuery object are also accessible like an array:
      $(“div”)[3]

      If you want to get a new jQuery object wich contains the third element you should use the .eq() function:
      $(“div”).eq(3)

  • Anonymous

    Mostly it’s very good that the “this” keyword refers to the current element – but if I’m doing a loop with .each() inside a class, and wants to access that class (not the elements own), the “this” keyword cannot be used anymore :(

    Just like:
    function foo() {
    this.bar = “bar”;
    this.foo = “foo”;
    this.foo_bar = function () {
    $(“li”).each(function () {
    return this.foo+”_”+this.bar; // won’t work
    });
    }
    }

    I know it’s a dumb example but it shows what I mean ;)
    Is there a workaround for this? So that I can access the above class?

    • Stefan

      It should work just fine, try this instead:

      function foo() {
      this.bar = “bar”;
      this.foo = “foo”;
      this.foo_bar = function () {
      $(“li”).each(function () {
      return this.foo + “_” + $(this).bar; // won’t work
      });
      }
      }

    • silver

      Maybe I’m misreading your problem, but isn’t that the same problem in any language where you use a variable with the same name in an inner loop?

      function foo() {
      this.bar = “bar”;
      this.foo = “foo”;
      this.foo_bar = function () {
      var parent = this;
      $(“li”).each(function () {
      return parent.foo+”_”+parent.bar; // won’t work
      });
      }
      }

    • http://twitter.com/gotofritz fritz

      I think I understand, I had the same problem – you need the $.proxy function
      http://api.jquery.com/jQuery.proxy/

      something like:
      $(“li”).each( $.proxy( function( i, domEl ){
      console.log( domeEl.id );//domEl is what this used to be
      return this.foo+”_”+this.bar; //this has become the context you passed with .proxy
      }, foo );
      (I am not sure about the last ‘foo’, but it’s a start :-)

      • Anonymous

        Thanks!
        That is exactly it! Much appreciated.
        In the meantime I’ve also been experimenting with scoping and such, so I’ve figured it out .. But the $.proxy function is in many case better and prettier ;)

      • http://www.google.com/profiles/garcia.dennis Dennis Garcia

        i have the same problem..
        please take a quick look at this :

        function llenado(){
        productoAr = new Array();
        impuestoAr = new Array();
        precioAr = new Array();
        cantidadAr = new Array();

        $(“#control tr”).each(function(index,valor){
        productoAr[index] = $(valor).find(“.idProductoSel”).html();
        impuestoAr[index] = $(valor).find(“.valImpuestoSel”).html();
        precioAr[index] = $(valor).find(“.valPrecioSel”).html();
        cantidadAr[index] = $(valor).find(“.valCantidadSel”).html();
        });
        }

        how can i assign values to those variables ?

        Thanks for your Help !

  • bigCSS

    What if I needed to find all the styles on an element I clicked? I can’t use “$(this).each” but I’m not sure how to get around it.
    $(this).bind(“click”,function(){
    $(this).each(function() {
    for (var i=0; i<this.style.length; i++) {
    console.log(this.style[i] + " = " + this.style.getPropertyValue(this.style[i]));
    }
    });
    });

  • Jesse

    Should I be using this function to loop through normal objects or arrays? Or should this only be used for DOM elements?

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

      This should be used for DOM elements. For normal objects or arrays, use jQuery.each().

    • Henry Fai Hang Chan

      only for an jQuery object. For other objects, arrays or Dom element collections (non-jQuery) use each. Performance wise, use for(var i=arr.length;i–;){}.

  • Bakaburg

    Is there a way to iterate using each() in the opposite direction?
    for example instead of this:
    for (var i = 0; i = 0; i–)…

    PS: I use each() also for normal arrays in this way:
    $(array).each(…);
    is less efficient then $.each()?

    • Henry Fai Hang Chan

      Performance wise, use for(var i=array.length;i–;){}.
      yes, less efficient with conversion to jQuery object as overhead, and $.each has other null checks and stuff.

  • Anonymous

    Here’s a quick example of using .each to iterate through an element’s attributes:

    Here I’m passed in the event.target from a mouseUp event

    function(target) {

    $.each($(target.attributes), function(index) {

    alert(“Attribute name: ” + target.attributes[index].name + ” Attribute value: ” + target.attributes[index].value);

    });

    }

    • Anonymous

      Thanks for the excellent example. I’m trying to loop through the attributes of an element like:

      link

      The example you gave seems really close to what I need … basically, I’m hoping someone can tell me what I should replace “target” with :)

      • Poke53281sys64738

        Thanks zimboden. This helped me a lot. I had to figure out the same thing as noobitis.

        target is a DOM object, which has an attributes array, but if you want to use this on a jquery object then you need to replace target with something like ($(“#link1″).get(0))

      • anonomys

        target is the dom element

  • https://www.google.com/accounts/o8/id?id=AItOawloP76G_bUxygeaQ06QAGP_8a10ilx6gF8 samsalisbury

    Ok, this may be a dumb question, but exactly what is the second parameter “Element” passed to the callback function?

    The method signature is given as:
    .each( function(index, Element) )

    However the subsequent documentation does not mention this parameter… I’m guessing it’s either a DOM element or a jQuery element, but which is it?

    • Anonymous

      Well, by running this in firebug console:

      $(‘li’).each(function(index, el) {console.log(el, el == this)});

      You can see that el is the HTML DOM Elements, and is the same as this.

  • http://www.sogyo.nl sjors miltenburg

    is there a reason why the continue keyword does not work within each? or is there an equivalent to use in this case?

    • http://twitter.com/stevenbs stevenbs

      continue (and break) will not work because they don’t have particular meaning outside the context of a loop structure (like for or while).

      you pass a function into each() and that function is called once per item in the list. since your code runs in the scope of that called function (as opposed to inside the scope of a loop) the continue or break, at best, are swallowed.

      To do a continue, at any point inside the function “return true” will simulate the same behavior as continue (that is, it will stop execution of everything else in the function, and go to the next item in the list)

      To do a break, “return false”. That will simulate a break (That is, no more code in the loop will run…it will not go to the next item in the list)

      Cheers

  • christasker

    how can I select elements that are dynamically generated?

    I have a form that has one input box and a button that places another input box every time it is clicked. before submitting I want to check that all inputs are filled in. $('input').each(…. only checks the first input box not the dynamically places ones.

    • Stefan Aichholzer

      Just add a new class to each new input you create, like so:

      var _input = $(“<input>”).attr({“type”: “text”, “name”, “inputName”, “class”: “formInput”});
      $(“#yourForm”).append(_input);

      And then loop through each using a class selector when you submit the form:

      $(“#yourForm .formInput”).each(function() {
      // Your code here
      });

      • Anonymous

        WOW, Thank you so much. I actually knew that, and thought I had done it. But when I read your post it suddenly dawned on me that maybe I forgot to add the class…. I did.

        You saved me a lot of time looking for some stupid solution to a problem I never had. lol

      • Anonymous

        WOW, Thank you so much. I actually knew that, and thought I had done it. But when I read your post it suddenly dawned on me that maybe I forgot to add the class…. I did.

        You saved me a lot of time looking for some stupid solution to a problem I never had. lol

      • http://twitter.com/mikemeyer Mike Meyer 

        using .live() would probably be a better approach, as in $(“form input”).live(function(){…});.live() is made for elements that are added after the document has loaded.Also, you could save a line on line 2 by using appendTo(form) instead of form.append().

  • http://www.1000words.dk Lars Clausen

    I keep finding myself writing 'find' functions for arrays, in the style of

    var found;
    jQuery.each(anArray, function() {
    if (this.something == other) {
    found = this;
    return false;
    }
    }

    where I would rather write

    var found = jQuery.find(anArray, function() { return this.something == other });

    Unfortunately, the find() function only operates on DOM elements. Any chance of either expanding it to work on non-DOM arrays, or making a similar one for arrays?

    • http://twitter.com/circusbear Erik Stainsby

      Consider $.grep(..) ?

      • Joe The Plunger

        'grep' is nice but not very performant for scenarios where you want to exit immediately upon finding a match.

  • Liugao206

    where do “this” and “$(this)” use?

  • Anonymous

    For arrays, the map function works well.
    IIRC it's
    myArray.map(function(el,index,wholearray))
    to make it go backward, it's
    myArray.slice(0).reverse().map…..

  • Chronicler

    Sorry if this is an easy to answer question, I'm not the most programming savvy. I'm making a small project website with HTML5 and rather than add an ID to each section tag, I will be coding a CMS that will create them and I want to auto-assign an ID to each section. I am using .each() for each section tag to apply an ID, but rather than post an incremental ID (1 for the first section, 2 for the second section), it applies the final count as the ID for both. Assistance is very appreciated, and the code is below.

    var sectID = 0;
    $(“section”).each(function() {
    $(this).attr(“id”, “section_” + (sectID + 1));
    })

  • flo

    IE 8 error: ” 'length' is Null or not an object”, line 552 (jQuery v. 1.4.2)

  • oakiedave

    sorry for the dumn question – why when you click the button a second time does it return to red? Shouldn't the color be set to empty stringby this line: this.style.color = “”; ?

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

      It's removing the style.color property from the element, but the style rule is still being applied within the <style> tag, where it is set to red

  • c00ch

    Is there a way to fire a function at the end of the last each interation?

  • Deepthi Somani

    very nice for begginers……

  • Jahangir

    I have 3 tables with same class name 'table-sort'. I would like to access those table by .each() and count the TR inside the tbody.
    is it $(“this tbody tr”).length?

    $('.table-sort').each(function(index) {
    var rowCount = $(“this tbody tr”).length; //not work , Could you please correct this?
    var rowCount1 = $(this).find('tbody > tr').length; //this is working fine
    alert(rowCount + '-' + rowCount1);
    });

  • Henry Fai Hang Chan

    Performance wise, use for(var i=array.length;i–;){}.
    yes, less efficient with conversion to jQuery object as overhead, and $.each has other null checks and stuff.

  • Egrunhaus

    Is there a way to iterate over a checkbox. I have a form on which there are 10 checkbox groups. These groups have varying numbers of boxes. I would like the first (topmost) group be the “master” group such that clicking one of the boxes in this master group will toggle an associated checkbox group to appear. And un-checking this box in the master group causes this same group to disappear. Similarly, the other boxes in the master group toggle the other associated groups to appear/disappear. Is there a way to do this using JQuery? Thanks in advance for any help. I'm struggling to wrap my head around the syntax.