jQuery each : 5 example to use jQuery.each() method

satinder singh / Updated : / 0 Comments

Understanding the jQuery .each() method and its uses: Here in this article will learn how and where we can use jquery $.each() method with live example. In other words how we can loop through our HTML element, array, object or JSON data by using jQuery .each(), Jquery’s foreach equivalent.

While writing code much time we need to use Loop, and all languages provide Loop.I.e., For Loop, Do while loop, etc.

I assume you all aware of using the loop that it offer a quick and easy way to do something repeatedly. And For loop repeats until a specified condition evaluates to false.

5 simple ways we use jQuery.each() function.

  1. jQuery.each() method to iterate over an Array (Foreach loop).
  2. jQuery.each() method to iterate over an Array of Object (Foreach loop).
  3. jQuery.each() method to iterate over html element (LI tag) (Foreach loop).
  4. jQuery.each() method to iterate over Table Row (tr) and get TD value.
  5. jQuery.each() method to iterate over Complex JSON Data (Foreach loop).

jquery each method to loop over table row tr

Let’s head to each way of understanding and using of jquery.each() function one by one, but before anything to start don’t forget to include jQuery Js file in your web page ( HTML Page).


#1 Use jQuery each function to iterate over an Array.

Let’s have an array object with some values in it. As you see below myArray is an array variable which holds values as some fruits name.

Now we want to display all fruit names one by one i.e., using jQuery each function we can iterate over this array variable, and display all the item value.

jQuery Code:

// here's my array variable
 var myArray = ["apple", "mango", "orange", "grapes", "banana"];

 $.each(myArray, function (index, value) {
 console.log(index+' : '+value);
 });

Output: So here the output which displays index and values

jquery each() method loop over array example
Try It Yourself ⇒

#2 Use jQuery each function to iterate over an Array of Objects.

Let us take another variable i.e., an array of object, with some data.

Now using jQuery .each() methods, we make a iterate over this JS object and display its records.

jQuery Code:

var obj= [
          { FirstName: "Andrea" , LastName:"Ely", Gender:"F"},
          { FirstName: "John" , LastName:"Shaw", Gender:"M"},
          { FirstName: "Leslie" , LastName:"Mac", Gender:"F"},
          { FirstName: "David" , LastName:"Millr", Gender:"M"},
          { FirstName: "Rehana" , LastName:"Rewa", Gender:"F"}
        ]

   $.each(obj, function (index, value) {
          var first_name=value.FirstName;
          var last_name=value.LastName;
          console.log(first_name+" "+last_name);
   });

OUTPUT: Here’s the output, that shows FirstName and LastName from object variable.

jQuery each method Loop through Array Object example

Isn’t it so simple to loop over records just using one simple method.


#3 Use jQuery each function to iterate over a list element.

Here in this example will loop over HTML element .i.e LI tag and display the text of li tag. Our HTML markup UL, Li tag as written below.

Now again we are going to use jquery .each() which will loop over Li tag and get the text of each LI tag and display its text.

HTML Markup:


<ul id="ul_Items">
<li class='fruits' >Apple</li>
<li class='fruits' >Mango</li>
<li class='automobile' >Honda Accord</li>
<li class='automobile' >Harley Davidson</li>
<li class='fruits' >Oranges</li>
<li class='fruits' >Grapes</li>
<li class='automobile' >Royal Enfield</li>
</ul>

jQuery Code:


$("#ul_Items li").each(function(){
     var self=$(this);
     console.log(self.text());
});

Another way we can achieve the same result i.e., as written below

$.each($("#ul_Items li"),function(){
     var self=$(this);
     console.log(self.text());
});

OUTPUT:

Using jquery each method Loop HTML element LI tag
Try It Yourself ⇒

Finally, we able to display the text of all li tag.


#4 Use jQuery each function to iterate over Table Row [ TR ].

Here we had an HTML table and added some dummy rows. Now we want to read these table cell value using jquery.

Now using the $.each() method, we fetch every table row cell value. I.e., each td value.


<table id="myTable" style="margin-left:50px;">
  <tr><th>Sr no</th><th>Name</th><th>Gender</th><th>Location</th></tr>
  <tr><td> 1</td><td>Satinder Singh</td><td> M </td><td> India </td></tr>
  <tr><td> 2 </td><td>Amit Sarna</td><td> M </td><td> France </td></tr>
  <tr><td> 3 </td><td>Andrea Ely</td><td> F </td><td> Brazil </td></tr>
  <tr><td> 4 </td><td>Leslie Mac </td><td> F </td><td> Australia </td></tr>
  <tr><td> 5 </td><td>Sonya David </td><td> F </td><td>America</td></tr>
</table>

jQuery Code:


$(".button").on('click', function () {

                $("#myTable tr").each(function () {
                    var self = $(this);
                    var col_1_value = self.find("td:eq(0)").text().trim();
                    var col_2_value = self.find("td:eq(1)").text().trim();
                    var col_3_value = self.find("td:eq(2)").text().trim();
                    var col_4_value = self.find("td:eq(3)").text().trim();
                    var result = col_1_value + " - " + col_2_value + " - " + col_3_value + " - " + col_4_value;
                    console.log(result);
                });
            });

Here’s we able to loop over html table row and fetch it td value.


#5 Use jQuery.each() method to iterate over Complex JSON Data

Now we are going to iterate over complex JSON data. While working with complex data we need to work with nested .each() to get respective data.

Here is our json data which has records as company name, and its multiple model id, model name respective.

What we have to do is, we want to display all company names with respected models name into the table.

JSON DATA: 

  var json = [{"Company_ID":"101",
  "Company_Name":"iPhone",
  "Models":[
    {"Model_ID":"101-M1","Model_Name":"iPhone SE"},
    {"Model_ID":"101-M2","Model_Name":"iPhone 11"},
    {"Model_ID":"101-M3","Model_Name":"iPhone X Pro"}]
 },
 {"Company_ID":"201",
  "Company_Name":"Vivo",
  "Models":[
    {"Model_ID":"201-M1","Model_Name":"Vivo Z1X Pro"},
    {"Model_ID":"201-M2","Model_Name":"Vivo 17 Pro"},
    {"Model_ID":"201-M3","Model_Name":"Vivo UD"}]
 }];

HTML Markup:

<table id="myTable" class="table">
<tr> 
<th>Company Name</th> 
<th>Models</th>
</tr>
</table>

Here we added a table tag on our webpage, which we use to display our JSON data. So here we are going to display company name , and its models name.

jQuery Code: Use of nested .each()  method 

var fragment="";
 var modelHTML="";
  $.each(json, function (index, value) {
 // now we have company name and its now,          
		 var Company_ID=value.Company_ID;
          var Company_ID=value.Company_Name;
		 
		  //now we do nested loop to get its models details.
         var objModel=value.Models;
		  
		  modelHTML +="";
		  
		   $.each(objModel, function (ind, val) {
		    var Model_ID=val.Model_ID;
              var Model_Name=val.Model_Name;			  
			   modelHTML +="<li>"+Model_Name+"</li>";
		   });
		   modelHTML +="<ul>";
		 
		 fragment +="<tr><td>"+Company_ID+"</td> <td>"+modelHTML+" </td></tr>";
   modelHTML="";
   });
   
   $("#myTable").append(fragment);

Here in variable modelHTML , where add all the models detail, which later append in variable fragment. Finally we append it to myTable which is our table element. By this we get the below output.
Output:

Jquery each over complex json data

BONUS: Let’s make it more practical real programming scenario, now what if a user wants to display only fruits. i.e., show only particular LI text whose text are fruits.

If you notice in our HTML markup, we have added a classname for each li tag .i.e fruits and automobile respectively. Now using this class, we can filter our Li tags. Let’s see here now we want to display.

jQuery Code:

$("#ul_Items li").each(function(){
   var self=$(this);
   // this will check if li has class fruits then only will display.
   if(self.hasClass("fruits")) 
   {
     console.log(self.text());
   }else 
   {
    // other code logic
    }
});

Another way is if you were sure to show only LI tag with having text as fruits. Then the best way is to select only those Li tag and loop over it, rather than loop over all Li tag which has shown in above example.

So now jquery code to loop over li tag having class as fruits look like as written below.

jQuery Code: To display li tag having text as fruits 

$("#ul_Items li.fruits").each(function(){
   var self=$(this);
   console.log(self.text());
});

OUTPUT:

jquery each loop over html element which contain specific class or active class

Conclusion: Here in this article we learn 5 different ways of how to use jQuery.each() method with live example. Inshort  if we want to loop over a simple array, complex JSON object or over HTML tag, i.e., loop over table row  tr or list tag, then using each() method we can achieve all.

For Reference:

You can also check these articles:

  1. Preview Image before upload it with jQuery in Asp.net.
  2. How to get the filename, size, type count in jQuery [input file, File Api].
  3. Create dynamic HTML table using jquery.
  4. How to remove table row tr in jquery on button click.
  5. Jquery: How to disable Button, Div, Anchor tag.

Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!


Post Comment


Your email address will not be published. Required fields are marked *