- jQuery - Home
- jQuery - Roadmap
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
jQuery Misc each() Method
The each() method in jQuery is used to iterate over a jQuery object, executing a function for each matched element. In other words, for each element in the matched set, the provided function is executed.
Syntax
Following is the syntax of jQuery Misc each() method −
$(selector).each(function(index,element))
Parameters
Here is the description of the above syntax −
- function: A function to execute for each matched element.
- index: The zero-based index of the current element in the matched set.
- element: The current DOM element being processed.
Example 1
In the following example, we are using the each() method to change text of each paragraph −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").each(function(index, element) {
$(element).text("Paragraph " + (index + 1));
});
});
</script>
</head>
<body>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</body>
</html>
After executing, It changes the text of each p element to "Paragraph 1", "Paragraph 2", and "Paragraph 3" based on their position in the set.
Example 2
In this example, we are changing background color of each list item using the each() method −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("li").each(function(index, element) {
var colors = ["lightblue", "lightgreen", "yellow"];
$(element).css("background-color", colors[index % colors.length]);
});
});
</script>
</head>
<body>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
</ul>
</body>
</html>
After executing, It sets the background color of each li element to "red", "green", or "blue" in a cyclic pattern based on their position in the set.