• jQuery Video Tutorials

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.

jquery_ref_miscellaneous.htm
Advertisements