jQuery $.each Method

What is each method?

The $.each method of jQuery makes it quite easier to iterate through different collection types in DOM. The collection type can be an object or arrays of jQuery. You might have seen or used the for each loop type in different programming languages, the jQuery each method is like that.

The $.each method has two variations as follows:

  • $.each() – in this method, you can use both array and object
  • $(selector).each() – in this method, you can only iterate through objects collection

Following are a few examples of using the $.each jQuery method. The examples will cover using each method in both ways.

An example of using $(selector).each jQuery method

In this example, I will show you how to use $(selector).each() jQuery method. As mentioned, you can only use objects in this method of jQuery. For that, I have created a parent div, which is basically a vertical menu. Inside the div, a menu is created by using <ul>, <li>, and <a> tags of HTML.

So hierarchy is: div >> ul >> li >> a

Look a live demo of this example by clicking the link or image below:

jquery each

See online demo and code

As you click on the link “Execute each method”, on the click event of that link I call $(selector).each method. In each method, the selector is the li (list item) element. This is followed by triggering an alert that will be shown for each li in the document.

The alert will show text associated with each list item by using .text property. Also, I have changed the background color of menu items by using hierarchy (parent/child).

You can see that the alert is shown five times i.e. for each list item in the document while color is changed for only those links that come under that div which contains that menu.

$.each example with a jQuery array

In this example, I will use $.each() method (in above demo, I used $(selector).each()). As mentioned earlier, you can use different collections including jQuery arrays in that each method to iterate over elements. The jQuery each index for array starts at 0. See following example with code followed by a little explanation:

The code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<script>
$(document).ready(function(){
var arr_example = [10,20,30,40,50,60,70,80,90,100];
$(".each_ex").click(function(){
    $.each (arr_example, function( index, value ) {
     $(".arr_ex").append(index + " " + value + "<BR>");
    });
});
});
</script>

<style>
.arr_ex{
word-spacing:50px;
padding-left: 5px;
height:200px;
width:100px;
border: solid 1px red;
}
</style>

</head>

<body>
    <button class="each_ex">Execute each method for array</button>
    <div>Index : Value</div>
    <div class="arr_ex">
    
    </div>

</body>
</html>

Sample Output:

jquery each array

I have created an array of ten elements in the script. As you click on the button, the $.each  method is called where you will specify array name, arr_example in that case. In jQuery each function, two parameters are given, the first is for the index that starts at zero and the value which is the corresponding array element’s value to that index.

Next, I used the $.append method to display the current index and value of the array. As the button is clicked, the array index and values will be displayed in the specified div element.

Another example of “each” with div element

In this example, I am going to use a few div elements with the same class names. The $.each method is attached to the link’s click event. As you click the link “Execute each method” the background color of every other div element will be changed to green.

jquery each div

Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<script>
$(document).ready(function(){

$(".each_ex").click(function(){
    $(".divcls").each(function(x) { if (x % 2) this.style.backgroundColor = "#008000"; });
});
});
</script>

<style>
.divcls{
    width:30%;
    height:30px;
    border:solid 1px black;
}
.each_ex{
    margin: 20px;
}
</style>
</head>

<body>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>
<div class="divcls"></div>

<a href="#" class="each_ex">Execute each method</a> 

</body>
</html>

When you click on the link, $.each method will execute, where inside the function I have dealt with div element’s divcls class. This line of code will make every other div’s background color to green.

$(".divcls").each(function(x) { if (x % 2) this.style.backgroundColor = "#008000"; });

 

A $(selector).each example with HTML table

In this example, I will use an HTML table to explain each method of jQuery. A table is created with a few rows and dummy data. The style is also created in internal CSS for the table header, the table row (tr), and table data. As the page loads, all table rows will have the same background. As you click on button “execute each method” the background color of every other row will be changed.

See online demo and code

jquery each table

You can see the same formula is applied as in the case of Div example. The color of even rows is changed. Similarly, you can add a CSS class to every other row.

Also in that example the each method is attached to click event of the link. If you want that at load time then simply use that code after document.ready statement:

$("tr").each(function(x) { if (x % 2) this.style.backgroundColor = "#fff"; });

 

and do not use click method. See the following example.

Adding new rows and each method example

In this example, a table is created with CSS style including table row background color. As demo page loads, every other table row’s background color will be changed by using each method. Also, a button is added, “Add row”, that will add a new row in the table. AS you click on the button not only a new row will be added, but jQuery each method will make every other row colored differently that includes newly added rows.

jquery each table add

The code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<script>
$(document).ready(function(){
$("tr").each(function(x) { if (x % 2) this.style.backgroundColor = "#fff"; });
    
    $(".addrow").click(function(){
    $(".tblcls").append("<tr><td>Table data</td><td>Table data</td></tr>");
    $("tr").each(function(x) { if (x % 2) this.style.backgroundColor = "#fff"; });
    });
});
</script>

<style>
.tblcls{
    border-collapse: collapse;
    border: 2px solid #006655;
  }
.tblcls th{
    border: 1px dashed black;
    color: #fff;
    background:#006655;
  }
.tblcls tr{
    padding:10px;
    border: 1px dotted black;
    color: #000;
    background:yellow;
  }
.tblcls td{
    padding:10px;
    border: 1px dotted black;
    color: #000;

  }
</style>
</head>

<body>
<button class="addrow">Add row</button>
<table class="tblcls">
  <tr>
      <th>Col 1</th>
      <th>Col 2</th>
  </tr>
  <tr>
      <td>Table data</td>
      <td>Table data</td>
  </tr>
  <tr>
      <td>Table data</td>
      <td>Table data</td>
  </tr>
  <tr>
      <td>Table data</td>
      <td>Table data</td>
  </tr>  
</table>
</body>
</html>

This line of code is first placed after document.ready() :

$("tr").each(function(x) { if (x % 2) this.style.backgroundColor = "#fff"; });

 

and it is also executed after each new row is added to the existing table.

jQuery each with the break

As mentioned earlier, the $.each method can be related to the foreach loop in different programming languages. The loops generally allow to break at a certain point of iteration either by using break or some other command relating to some other language.

This can be done quite easily in $.each method by using the return statement. By making the callback function false, the loop will stop or break. Following is an example of breaking $.each once it is called in the click event:

jquery each break

Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<script>
$(document).ready(function(){
var arr_example = [10,20,30,40,50,60,70,80,90,100];
$(".each_ex").click(function(){
    $.each (arr_example, function( index, value ) {
     $(".arr_ex").append(index + " " + value + "<BR>");
     return ( value !== 50 );
    });
});
});
</script>

<style>
.arr_ex{
word-spacing:50px;
padding-left: 5px;
height:200px;
width:100px;
border: solid 1px red;
}
</style>

</head>

<body>
    <button class="each_ex">Execute each method with return</button>
    <div>Index : Value</div>
    <div class="arr_ex">
    
    </div>

</body>
</html>

We created a loop just like in the above array example with ten elements. Inside the “each” function this line is placed:

return ( value !== 50 );

That means as the value reaches 50 it will return or break. If you do not use this, all elements of the array will be printed in div element, however, in that case just five elements are displayed.