jQuery Each – The Complete Guide for Coders

jQuery Each – The Complete Guide for Coders

The jQuery each() is used to iterate over each element of an Object, array like Objects and arrays. It can also be used to loop over DOM elements.

jQuery each() Syntax

$(selector).each(function(index,element))
Parameter Description
function(index,element) A required function to run for each matched element.

  • index – The index position of the selector.
  • element – The current element of the selector.

Let’s iterate over anchor tags and extract their href attribute of any page.

$("a").each(function (index, value) { 
  console.log("anchor" + index + ":" + $(this).attr("href")); 
}); 

When executing the above code in a web page, it gives the following output.

jquery each output

The jQuery each method can be also used to iterate over arrays, objects and array like objects.

In this case, the object to loop over, is given as the first argument like shown below:

$.each(object, function (index, value){
//code
});

Let us examine the different examples of jQuery each method–

1. jQuery Each Array Example

Iteration over an array can be doing easily with the each() method. See the below code:

var names = ["yogi","john","gia","michael","czar"];
$.each(names , function (index, value){
  console.log("Array Current Index is: "+ index + " :: Value is: " + value); 
});

Output:
Array Current Index is: 0 :: Value is: yogi
Array Current Index is: 1 :: Value is: john
Array Current Index is: 2 :: Value is: gia
Array Current Index is: 3 :: Value is: michael
Array Current Index is: 4 :: Value is: czar

2. jQuery Each For Loop Example

You can use the jQuery Each method instead of For Loop. Let’s find how it is possible.

The For Loop Example
var allDiv = $("div");

for ( var i=0; i<allDiv.length; i++) {
    // use allDiv[i] for accessing each one
}

The above for loop iterates over every div element of the page. This can be done by the .each() method also.

$("div").each(function(index,value) {
    //$(this) for accessing each of them
}
jQuery Each Chaining Example

You can do chaining with .each() method and this is not possible with for loop. The following code sets the background to purple color, for every odd paragraph.

$("p").each(function (index, value) {
    // for all paragraph
}).filter(":odd").each(function (index, value) {
    $(value).css("background-color", "purple");
    // Or $(this).css("background-color", "purple");
});

jquery each chaining example

3. jQuery Each JSON Example

Use jQuery Each to iterate over JSON and extract information from it.

In the below code I will show how to extract Country name and their capitals from a JSON.

var json = [{ "US": "Washington DC" }, { "India": "New Delhi" }, { "China": "Beijing" }, 
{ "Japan": "Tokio" }];

$.each(json, function (index, value) {
    $.each(this, function (index, value) {
        console.log(index + " :: " + value);
});

jQuery each JSON example

I used a nested .each() for extracting information from this JSON. The outer .each() loops through each JSON object while the inner one gets their values.

4. jQuery .each() XML Example

jQuery .each() lets you to iterate over XML files too. Let us see an example.

I have an XML that contains countries and their capitals.

<?xml version="1.0" encoding="utf-8" ?>
<countries>
  <country>
    <name>US</name>
    <capital>Washington DC</capital>
  </country>
  <country>
    <name>India</name>
    <capital>New Delhi</capital>
  </country>
  <country>
    <name>China</name>
    <capital>Beijing</capital>
  </country>
  <country>
    <name>Japan</name>
    <capital>Tokio</capital>
  </country>
</countries>

To extract country names and their capitals from it use jQuery .each() method like this:

var xml = "<countries><country><name>US</name><capital>Washington DC</capital></country><country><name>India</name><capital>New Delhi</capital></country><country><name>China</name><capital>Beijing</capital></country><country><name>Japan</name><capital>Tokio</capital></country></countries>";

$(xml).find("country").each(function (index, value) {
    console.log($(this).find("name").text()+ " :: " + $(this).find("capital").text());
});

In this example I have used .find() to find the country node in the XML and then iterate over each of them with .each() method.

Inside the .each() block, I extracted the name and capital using .find() method.

jquery each xml example

6. jQuery .each() Class Example

Elements which are assigned a certain class can be iterated with the jQuery each method. Suppose our web page has some paragraph (p elements) that contains ‘script’ and ‘language’ classes.

See the below HTML:

<p class="script">jQuery</p>
<p class="language">C#</p>
<p class="script">JavaScript</p>

To select all the p elements having class ‘script’ I can use the jQuery each method:

$(".script").each(function (index, value) {
    console.log($(this).html())
});

It will give jQuery and JavaScript only and not C#.

jquery each class example

7. jQuery .each() Animation Example

Use jQuery Each for creating rich animation effects. In the below example there are 3 blocks, on clicking the button I toggle their width with easing animation effect.

I also apply index-dependent delay of 800 milliseconds on each of them (0,800, 1600 milliseconds).

This gives me eye pleasing toggling animation effect.

The 3 blocks are:

<div class="block"></div>
<div class="block"></div>
<div class="block"></div>

The jQuery Code for this:

$(".block").each(function (index, value) {
    $(this).delay(index * 800).animate({
        width: "toggle"
    }, "easing");
});

8. jQuery .each() Arithmetic Addition Example

Addition of numbers in an array can be performed with jQuery .each method like:

var sum=0;
var numbers = [10,20,30,40,50];
$.each(numbers , function (index, value){
  sum=sum+value;
});
Console.log(sum); 

I took a sum variable, then iterated over the numbers array and kept on adding them to the sum variable. Finally outputting the sum at the end.

Stop Loop Early

It is not necessary to wait for the whole loop to execute. You can leave the loop early by using return false;.

Suppose you are searching for a name in an array of strings. You use the jQuery Each method for looping, once you find your name you can get out of the loop with return false;.

var search = "michael";

var loopValue = "";
var names = ["yogi", "john", "gia", "michael", "czar", "jack", "cara", "sofie"];
$.each(names, function (index, value) {
    loopValue += "Index: " + index + " :: " + "Value: " + value + "<br/>";
    if (search == value)
        return false;
});

I am searching name ‘michael’, for this I am checking each name with if statement. When found, I am coming out of the loop through return false; statement.

The output which I get is given below:

jquery each stop loop early

It clearly shown the loop is executing till the index number 3 and then coming out.

DEMO DOWNLOAD

jQuery Each – My Final Words

Now you understand that jQuery Each is such a valuable method and we can use it to make your code much shorter and smarter.

Remember: $.each() and $(selector).each() are two different methods defined in two different ways.

Let your friends know about this method so kindly share this tutorial on your social accounts, sharing links given below.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.