How to use each() in jQuery?

The jQuery each function is used to iterates through DOM elements similar to a foreach loop in other languages. This function iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. The call back function is triggered in the context of the current DOM element, so you can use this keyword to refer the currently matched element. Syntax
$(selector).each(function(index,element))
  1. index - The index position of the element
  2. element - The current element
$("li").each(function(index){ alert(index + " - " + $(this).text()) });
<ul> <li>Red</li> <li>Blue</li> <li>Green</li> </ul>
run this source code Browser View
  • Red
  • Blue
  • Green


Full Source
<!DOCTYPE html> <html lang="en"> <head> <title>jQuery each() function</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('button').click(function() { $("li").each(function(index){ alert(index + " - " + $(this).text()) }); }); }); </script> </head> <body> <ul> <li>Red</li> <li>Blue</li> <li>Green</li> </ul> <button>Get Values</button> </body> </html>

Loop Through Arrays

jQuery $.each() works for objects and arrays both.
var colors = ['red', 'blue', 'green']; $.each(colors , function (index, value){ alert(index + ':' + value); });
run this source code Browser View
Full Source
<!DOCTYPE html> <html lang="en"> <head> <title>jQuery each Array(':visible')</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('button').click(function() { var colors = ['red', 'blue', 'green']; $.each(colors , function (index, value){ alert(index + ':' + value); }); }); }); </script> </head> <body> <button>Try it</button> </body> </html>