The community is working on translating this tutorial into Arabic, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".
Looping with the each() method
Iterating through data using loops is a very essential part of programming - also in JavaScript, where you will find the for and the while loops for doing just that. However, most recent programming languages also include the foreach loop. Using the foreach loop makes it a lot easier to access the current item in the loop and is perfect for iterating over lists of objects.
Unfortunately, JavaScript doesn't include the foreach() loop, so when we're using plain JavaScript, we're forced to use a for() loop, like this:
<script type="text/javascript">
var arrayOfUsers =
[
{ Id: 1, Name: "John Doe" },
{ Id: 2, Name: "Jane Doe" },
{ Id: 3, Name: "Joe Doe" }
];
for(var i = 0; i < arrayOfUsers.length; i++)
{
var user = arrayOfUsers[i];
document.write("User #" + user.Id + ": " + user.Name + "<br>");
}
</script>
Short explanation: We define an array of user objects and then we loop over them with the for() loop. On each iteration, we fetch the actual user from the array with the indexer variable (called i) and then we do a simple print of the user data. The for loop is a bit clumsy for something like this, as you can see - right from the very verbose declaration where we have to define an indexer, state a condition for how long the loop should run and even increment the indexer on each iteration.
Fortunately for us, the good folks on the jQuery team wants to save us from all this trouble, so they have implemented a foreach loop that we can use. Because this is just an abstraction on top of a regular loop, it doesn't look exactly like the foreach loop that you may know from other programming languages. Let me illustrate how it works using the same example as before:
<script type="text/javascript">
var arrayOfUsers =
[
{ Id: 1, Name: "John Doe" },
{ Id: 2, Name: "Jane Doe" },
{ Id: 3, Name: "Joe Doe" }
];
$.each(arrayOfUsers, function(i, user)
{
document.write("User #" + user.Id + ": " + user.Name + "<br>");
});
</script>
Once again, we define the exact same array of users but then we use the jQuery each() method to loop through the data. It works by specifying (at least) two parameters: An array or an object to loop through and then a function to be called on each iteration. This function is called with two parameters, which we can use (if we want to): The current index of the item and the item it self. In this case, we call the two parameters i and user, but you are of course free to call them whatever makes sense to your case. For this situation, we don't really need the indexer, but we definitely need the current item (user), which we use just like before: To output data about the user.
Using break and continue with the each() loop
A core piece of functionality in a regular loop is the ability to skip to the next iteration (using the continue keyword) or leaving the loop entirely using the break keyword. This can be done for the each() loop too, but since this is a special construct created by jQuery and not an actual loop, it's done in a slightly different way. Let's see another example:
<script type="text/javascript">
var arrayOfUsers =
[
{ Id: 1, Name: "John Doe" },
{ Id: 2, Name: "Jane Doe" },
{ Id: 3, Name: "Joe Doe" }
];
$.each(arrayOfUsers, function(i, user)
{
if(user.Id == 1)
return true; // Continue
if(user.Id == 3)
return false; // Break
document.write("User #" + user.Id + ": " + user.Name + "<br>");
});
</script>
We use the exact same set of data as before, but this time we have added some logic - if the user has the Id of 1, we skip to the next iteration and if the user has the Id of 3, we completely abandon the loop. This would normally be done using continue and break respectively, but since we're inside a function and not an actual loop, we use the return keyword instead. To continue, we return true and to break we return false. jQuery then translates this into the behavior of continue and break for us.
Looping over DOM elements
We have just used the static version of the each() method, which is a cool utility function that gives us access to a foreach() loop when dealing with regular JavaScript arrays or object properties. However, jQuery also has a non-static version of the each() method, that you can use to loop through a collection of DOM elements that you fetch with one of the many jQuery selectors. Let's jump straight into an example, so you can see what I'm talking about:
<ul>
<li>John Doe</li>
<li>Jane Doe</li>
<li>Joe Doe</li>
</ul>
<script type="text/javascript">
$(function()
{
$("li").each(function(index, listElement)
{
$(listElement).append(" is number " + (index + 1));
});
});
</script>
We have a small HTML unordered list, with some names in it. We then use a simple jQuery element-based selector to select all list item (<li>) elements and then call the each() method on it. We supply it with a single parameter which is a function that should be called for each iteration in the each() method. Like in the previous examples, this function supplies us with two parameters, to be used within the loop - an index and the actual element, which we have called index and listElement in this case.
Inside the loop, we append a piece of text to the element in question and just for fun, this text is made by using the current index of the iteration. This serves as a nice way of demonstrating how we can use the parameters supplied to us by jQuery.
Summary
The each() method is a great help - in both the static version, which we can use for iterating over JS arrays and the non-static version, which is great for looping through selected elements. Both versions allows you to skip to the next iteration or exit the loop using return true and return false respectively, as previously demonstrated in the example.