jQuery Each: 7 Coding Examples that you can’t miss as a Developer

jQuery Each: 7 Coding Examples that you can’t miss as a Developer
You will now learn all the ways to use the jQuery Each method from this tutorial. This is the most complete guide to master this method.

The best part?

I’m going to show you 7 ways to use jQuery Each method in your website.

In short: if you want to implement .each() method, then you’ll love this guide.

Let’s get started.

The jQuery .each() function 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 all the anchor tags in a page, and extract their href attribute’s value.

$("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

Notice: In the above code I use the jQuery each this object to refer the current element and get it’s values.

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 function:

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

Do you want to make high quality AJAX features in your website. Then take my advice, learn jQuery AJAX function now by visiting this tutorial.

2. jQuery Each For Loop Example

You can use the jQuery Each method instead of the For Loop. Let’s find out 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 in 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 the chaining of the .each() method, and this is not possible with the for loop. See the below code which sets the background to purple color, for every odd paragraph element.

$("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 the varaible’s value (which is a 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, you 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() method to find the country node in the XML. Then I am iterating over each of them with .each() method. Inside the .each() block, I extracted the name and capital using .find() method.

jquery each xml example

5. jQuery .each() Class Example

Elements which are assigned a certain class can be iterated with the jQuery each method.

Suppose the web page has some paragraph (p elements) that contains ‘script’ and ‘language’ classes, as shown by the below code:

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 like:

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

It will give the strings – jQuery and JavaScript only and not C#.

jquery each class example

6. 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 applied 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");
});

7. 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.

jQuery Each Break to stop loop early

It is not necessary to wait for the whole loop to execute. You can break out of the loop by using the return false; statement.

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 an if statement. When found, I am coming breaking out of the loop through the return false; statement.

The output which I get here is given below:

jquery each stop loop early

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

DOWNLOAD

jQuery Each – My Final Words

The jQuery Each method is such a valuable method and you 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.

Do you have any question? Use the comments section to reach out to me. Let your friends know about this method so kindly share this tutorial on your social accounts, sharing links given below.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate