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 an 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.
Note: The $.each()
function internally retrieves and uses the length
property of the passed collection. So, if the collection has a property called length
â e.g. {bar: 'foo', length: 10}
â the function might not work as expected.
$.each([ 52, 97 ], function( index, value ) { alert( index + ": " + value ); });
This produces two messages:
0: 52
1: 97
If an object is used as the collection, the callback is passed a key-value pair each time:
var obj = { "flammable": "inflammable", "duh": "no duh" }; $.each( obj, 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.
The array to iterate over.
The function that will be executed on every object.
The object to iterate over.
The function that will be executed on every object.
Iterates through the array displaying each number as both a word and numeral
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery.each demo</title> <style> div { color: blue; } div#five { color: red; } </style> <script src="https://code.jquery.com/jquery-1.10.2.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( i, val ) { $( "#" + val ).text( "Mine is " + val + "." ); // Will stop running after "three" return ( val !== "three" ); }); jQuery.each( obj, function( i, val ) { $( "#" + i ).append( document.createTextNode( " - " + val ) ); }); </script> </body> </html>
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 ); });
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 ); });
Please login to continue.