[email protected]      beta
Donate

jQuery $.each() : How and where to use jQuery ForEach Loop [5 ways]

Understanding the jQuery ForEach Loop and its uses .i.e $.each() : Here in this article will learn how and where we can use jquery $.each function. In other words how we can loop through an 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 ways we use jQuery  $.each() function.

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

 

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


# Use jQuery each function Loop through an Array.

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

Now we want to display each fruit name i.e., using jquery each function will loop over this array variable and display each 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:

jquery each() method loop over array example

 

Try It Yourself ⇒

So here the output which displays index and values


#Use jQuery each function Loop through 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 loop 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:

jQuery each method Loop through Array Object example

 

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


#Use jQuery each function Loop through 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 by using jquery .each() 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.

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

 

 


#Use jQuery each function Loop through 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>

jQuer 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);
                });
            });

Conclusion: Here in this article we learn how to use jquery $.each() method in many different ways. We can use to loop over a simple array, complex JSON object or over HTML tag, i.e., loop over table row or li 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!

 

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }



Post Comment


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