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:

Comments

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

  • Please do post corrections or additional examples for .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.
  • Bakaburg
    Is there a way to iterate using each() in the opposite direction?
    for example instead of this:
    for (var i = 0; i < array.length; i++)…

    this:
    for ( var i = array.length - 1; i >= 0; i--)…

    PS: I use each() also for normal arrays in this way:
    $(array).each(…);
    is less efficient then $.each()?
  • Jesse
    Should I be using this function to loop through normal objects or arrays? Or should this only be used for DOM elements?
  • This should be used for DOM elements. For normal objects or arrays, use jQuery.each().
  • 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]));
    }
    });
    });
  • sunear
    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?
  • 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 :-)
  • sunear
    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 ;)
  • 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
    });
    }
    }
  • 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
    });
    }
    }
  • analystz
    anyway to call a particular object in a collection directly? like: $("div").item(3) ??