.each() loop
Learn about .each() by EasyProgramming.net
by Nazmus Nasir
HTML
<!-- Easy jQuery - working with .each() - #11 -->
<p>
Welcome to the 11th Easy jQuery Tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. In this tutorial, let's learn working with the .each() method in jQuery.
</p>
<p>
This is very similar to the JavaScript forEach loop as shown on <a href="https://www.easyprogramming.net/javascript/js_array_forEach_method.php">Easy Programming</a>.
</p>
<p>
The <code>.each()</code> loop can be written two different ways. The frst way lets you select an array object and pass in a call backfunction as the one and only argument as shown below:
</p>
<pre>
$(array).each(function(index, item){
execute code;
the 'item' is the actual value;
'index' is the index number (e.g. i);
})
</pre>
<p>
The second way lets you select jQuery as the object itself and pass in two arguments. The first being the array and second being the callback function.
</p>
<pre>
$.each(array, function(index, item){
execute code;
the 'item' is the actual value;
'index' is the index number (e.g. i);
})
</pre>
<h2>
Let's practice:
</h2>
<ol id="output"></ol>
<ol id="output2"></ol>
<br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
JavaScript
var myArray = ['Boston', 'New York', 'Chicago', 'Miami', 'Los Angeles', 'Dallas', 'Seattle'];
$(myArray).each(function(i, item){
$("#output").append($("<li>").append(item));
});
$.each(myArray, function(i, item){
$("#output2").append($("<li>").append(item));
});