jQuery each() Method



The each() method in jQuery iterates over a jQuery object, executing a specified function for each matched element in the set.

This method accepts a required parameter: a "callback function" that will be executed for every element in matched set. The callback function takes two additional parameters: "index" and "element". The "index" parameter represents the index position of the current element within the set, while the "element" parameter represents the current element being iterated over.

Syntax

Following is the syntax of each() element in jQuery −

$(selector).each(function(index,element))

Parameters

This method accepts the following parameters −

  • function(index, element): The function to execute for each element in the set.

Example 1

In the following example, we are using the each() method to iterate over each <li> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('li').each(function(index, element) {
        alert('Index: ' + index + ', Element: ' + $(element).text());
    });
});
</script>
</head>
<body>
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
</body>
</html>

When we execute the above program, for each li element, an alert is shown displaying its index.

Example 2

In this example, the each() method will iterate over each <input> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('input[type="text"]').each(function(index, element) {
        alert('Index: ' + index + ', Value: ' + $(element).val());
    });
});
</script>
</head>
<body>
<input type="text" value="Input 1"><br>
<input type="text" value="Input 2"><br>
<input type="text" value="Input 3">
</body>
</html>

For each input element found, an alert is shown displaying its index within the set of matched elements and its value.

jquery_ref_traversing.htm
Advertisements