$.each Utility
Loop over arrays and objects with the $.each helper.
Syntax
$.each(collection, function (key, value) { ... });There are two each forms:
$(selector).each(fn)— loops over matched DOM elements.$.each(collection, fn)— loops over any array or object.
$.each(["a", "b", "c"], function (index, value) {
console.log(index, value);
});Example
Loading editor…
Press Run to see the result.
When to use it
- A currency converter uses $.each() on a rates object to build a dropdown option for every currency code.
- A chart builder uses $.each() over an array of data points to compute the maximum value before scaling the axes.
- A batch update script uses $.each() to send a separate AJAX request for each item in a selected list.
More examples
Iterate over an array with $.each()
$.each() calls the callback with the index and value for every element in the array.
<ul id="fruits"></ul>
<script>
$(function () {
var items = ["Apple", "Banana", "Cherry"];
$.each(items, function (index, value) {
$("#fruits").append("<li>" + index + ": " + value + "</li>");
});
});
</script>Iterate over a plain object
When the first argument is a plain object, $.each() iterates its own enumerable properties as key-value pairs.
<dl id="info"></dl>
<script>
$(function () {
var user = { name: "Alice", role: "Admin", active: true };
$.each(user, function (key, val) {
$("#info").append("<dt>" + key + "</dt><dd>" + val + "</dd>");
});
});
</script>Break early out of $.each()
Returning false from the callback stops $.each() early, equivalent to a break statement in a for loop.
<p id="found"></p>
<script>
$(function () {
var scores = [42, 78, 95, 61, 88];
var firstPassing;
$.each(scores, function (i, score) {
if (score >= 90) {
firstPassing = score;
return false; // stops iteration
}
});
$("#found").text("First passing score: " + firstPassing);
});
</script>
Discussion