jQuery | Misc each() Method

The each() Method in jQuery is used to specify the function to run for each matched element.

Syntax:

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

Parameters: This method accepts single parameter function(index, element) which is mandatory. It is used to run for each matched element. It contains two parameters.

  • index: It holds the index position of selector element.
  • element: It holds the current element.

Example 1: This example use each() method to display each paragraph element.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head
    <title>
        jQuery Misc each() Method
    </title>
      
    <script src=
    </script>
</head
  
<body style="text-align:center;">
  
    <h1 style = "color:green;" >  
        GeeksForGeeks
    </h1>  
      
    <h2>jQuery each() Method</h2>
  
    <button>Click</button>
      
    <p>Geeks1</p>
    <p>Geeks2</p>
    <p>Geeks3</p>
      
    <!-- Script use each() method -->
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("p").each(function() {
                    alert($(this).text())
                });
            });
        });
    </script>
</body>
  
</html>  

chevron_right


Output:

  • Before Click on the Button
  • After Click on the Button


Example 2: This example use each() method to display paragraph element.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head
    <title>
        jQuery Misc each() Method
    </title>
      
    <script src=
    </script>
</head
  
<body style="text-align:center;">
  
    <h1 style = "color:green;" >  
        GeeksForGeeks
    </h1>  
      
    <h2>jQuery each() Method</h2>
  
    <button>Click</button>
      
    <p>Geeks1-Geeks2-Geeks3</p>
      
    <div style="color:lightgreen;"></div>
      
    <!-- Script use each() method -->
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("p").each(function(){
                    $("div").text($(this).text())
                });
            });
        });
    </script>
 </body>
  
</html>  

chevron_right


Output:

  • Before Click on Button
  • After Click on Button


  • My Personal Notes arrow_drop_up

    Small things always make you to think big

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.