jQuery: The Write Less, Do More JavaScript Library

Utilities/jQuery.each

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Utilities

jQuery.each( object, callback )

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.

The callback has two arguments:the key (objects) or index (arrays) as the first, and the value as the second.

If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Other return values are ignored.
Arguments:
objectObject
The object, or array, to iterate over.
callbackFunction
The function that will be executed on every object.
function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

  this; // == valueOfElement

  return booleanKeepGoing; // optional, unless false 
                           // and want to stop looping
}

Examples:
Filters the original array of numbers leaving that are not 5 and have an index greater than 3. Then it removes all 9s while inverting it.

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    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>
  <style>
  div { color:blue; }
  div#five { color:red; }
  </style>
</head>
<body>
  <div id="one"></div>
  <div id="two"></div>
  <div id="three"></div>
  <div id="four"></div>
  <div id="five"></div>
</body>
</html>

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

$.each( [0,1,2], function(i, n){
  alert( "Item #" + i + ": " + n );
});

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

$.each( { name: "John", lang: "JS" }, function(i, n){
  alert( "Name: " + i + ", Value: " + n );
});

NameType