Back to: jQuery Tutorials
jQuery Each Method with Examples
In this article, I am going to discuss jQuery Each Method with Examples. Please read our previous article, where we discussed jQuery Disabled and Enabled Selector. At the end of this article, you will understand everything about jQuery Each Method.
jQuery Each Method
The jQuery Each method is used to iterate over the items of a collection. This iterates over a jQuery object executing a function for each element of the collection. For each item in the collection, the anonymous function is called. The index of the element and the element itself is passed to the anonymous function. Following is the syntax to use the jQuery Each method.
The jQuery each() method takes a callback function which takes two optional parameters Index and the current DOM element i.e. the current item or element over which the iteration is going. Each time the callback runs, it is passed the current loop iteration, beginning from 0. Let us understand the need and use of jQuery each function with examples.
Example:
In the below example, we have 3 <div> elements. By using each() method, we are iterating over those and for each div element, we are printing the index, their ID, and the text inside them on the console.
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <h3>jQuery Each Method</h3> <section> <div id="1st">This is 1st text</div> <div id="2nd">This is 2nd text</div> <div id="3rd">This is 3rd text</div> </section> </br> <button class="demo">Click Me</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $('.demo').click(function () { $('div').each(function(index, item){ console.log(`${index} ${$(item).attr('id')} ${$(item).text()}`) }); }); }); </script> </body> </html>
Now run the above code and you will see the following output in the browser.
Now, open the browser developer tool by pressing the F12 key and open the console tab. Then click on the Click Me button and you should get the following log in the console tab.
The callback is fired in the context of the current DOM element, the keyword ‘this’ refers to the element. So, we can use this keyword instead of the item parameter. Modify the script section of the previous example as shown below and it should work as expected as the previous example.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $('.demo').click(function () { $( 'div' ).each(function(index){ console.log(`${index} ${$(this).attr('id')} ${$(this).text()}`) }); }); }); </script>
Example:
In the below example, we are applying CSS to every <div> element present in our DOM
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <h3>jQuery Each Method</h3> <section> <div id="1st">This is 1st text</div> <div id="2nd">This is 2nd text</div> <div id="3rd">This is 3rd text</div> </section> </br> <button class="demo">Click Me</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $('.demo').click(function () { $('div').each(function(){ $(this).css('backgroundColor','skyblue') }); }); }); </script> </body> </html>
Now, run the above code and then click on the Click Me button and you should get the following output in the browser.
Exit from Iteration using jQuery
If we want to exit from the loop at any stage of the iteration then we need to use {return false}. In the below example, as soon as the div text is matching with “This is 5th text”, our loop ends there immediately. Notice that the iteration has been performed only with 4 div elements
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <h3>Exit From jQuery Each Method</h3> <section> <div id="1st">This is 1st text</div> <div id="2nd">This is 2nd text</div> <div id="3rd">This is 3rd text</div> <div id="4th">This is 4th text</div> <div id="5th">This is 5th text</div> <div id="6th">This is 6th text</div> <div id="7th">This is 7th text</div> <div id="8th">This is 8th text</div> </section> </br> <button class="demo">Click Me</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $('.demo').click(function () { $('div').each(function () { if ($(this).text() === 'This is 5th text') { return false } $(this).css('backgroundColor', 'skyblue') }); }); }); </script> </body> </html>
Now, run the above code and then click on the Click Me button and you should get the following output in the browser and notice that the CCS is applied up to the fourth div element.
Implicit Iteration in jQuery
Most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection, a process known as implicit iteration. When this occurs, it is often unnecessary to explicitly iterate with the .each() method. Let’s see an example.
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <h3>Implicit Iteration in jQuery</h3> <section> <ul> <li>This is a list</li> <li>This is a list</li> <li>This is a list</li> <li>This is a list</li> <li>This is a list</li> <li>This is a list</li> </ul> </section> </br> <button class="demo">Click Me</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $('.demo').click(function () { $('li').each(function () { $(this).css('color', 'red'); }); }); }); </script> </body> </html>
Now, run the above code and then click on the Click Me button and you should get the following output in the browser
Here, we are explicitly adding a CSS to every <li> element. But here $( ‘li’ ) returns a collection in which we can directly apply the CSS. This will iterate over every list item implicitly. To do so, please modify the script section as shown below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $('.demo').click(function () { $('li').css('color', 'red') }); }); </script>
With the above changes in place, if you run the code, then you will get the same output as the previous example as shown in the below image.
jQuery.each() Utility function
The jQuery.each() Utility function is a generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
Difference between $(‘selector ).each and $.each():
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through this keyword, but JavaScript will always wrap this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.
Reference: https://api.jquery.com/jquery.each/
Syntax:
Let us understand this with some examples.
Example: jQuery.each() Method with array
In the below example, we have an array and we can access all of its element by this $.each() function
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <h3>jQuery Each Function</h3> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { let arr = ["HTML","CSS","JavaScript","jQuery","React"]; $.each(arr, function(index, item){ console.log(`Index no ${index} : Item = ${item}`) }); }); </script> </body> </html>
Now run the above code and then open the browser developer tool by pressing the F12 key and have a look at the console and you should see the following logs in the console.
Example: jQuery.each() Method with object
In the below example, we have an object and we can access all of its key and value pair by using the $.each() function.
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <h3>jQuery Each Function</h3> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { let obj ={ name : 'John', age : 22, job : 'Web Developer', hobby : 'cricket', } $.each( obj, function(key, val){ console.log( `Key = ${key} : Value = ${val}` ) }); }); </script> </body> </html>
Now run the above code and then open the browser developer tool by pressing the F12 key and have a look at the console and you should see the following message in the console.
Performance considerations when using jQuery each Method
Let us understand this with an example. Please have a look at the below code.
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <ul> <li>JavaScript</li> <li>jQuery</li> <li>Angular</li> <li>ReactJS</li> <li>NodeJS</li> </ul> <div id="ResultDiv"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function () { $('li').each(function () { $('#ResultDiv').html($('#ResultDiv').html() + '<br/>' + $(this).text()) }); }); </script> </body> </html>
From a performance point of view, there are 2 problems with the above code.
- First Problem: The jQuery needs to search the DOM for div element with id ResultDiv, for each list item in the collection. As we have 5 list items, the jQuery searches the DOM 5 times for the same div element with id ResultDiv. We can improve the performance of the above code \ by caching the ResultDiv element.
- Second Problem: The DOM element (div element with id ResultDiv) is updated for each iteration. Again, this is bad for performance. To improve the performance, we can build a string variable with the required data on each iteration. Once the loop has been completed, update the DOM element with the value that is present in the string variable. This will ensure that the DOM element (div element with id ResultDiv) is updated only once and this is much better for performance.
The following code addresses the above two problems and provides much better performance.
<!DOCTYPE html> <html> <head> <title>jQuery Each Function</title> </head> <body> <ul> <li>JavaScript</li> <li>jQuery</li> <li>Angular</li> <li>ReactJS</li> <li>NodeJS</li> </ul> <div id="ResultDiv"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { var result = ''; $('li').each(function () { result += '<br/>' + $(this).text(); }); $('#ResultDiv').html(result); }); </script> </body> </html>
In the next article, I am going to discuss jQuery Method Chaining with Examples. Here, in this article, I try to explain jQuery Each Method with Examples and I hope you enjoy this jQuery Each Function article.