jQuery Misc each() Method (original) (raw)

Last Updated : 04 Jul, 2023

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.

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

html `

jQuery Misc each() Method
<script src=

"" title="undefined" rel="noopener noreferrer">https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">

<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>

`

Output:

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

html `

jQuery Misc each() Method
<script src=

"" title="undefined" rel="noopener noreferrer">https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">

<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(){
                <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">&quot;</mi><mi>d</mi><mi>i</mi><mi>v</mi><mi mathvariant="normal">&quot;</mi><mo stretchy="false">)</mo><mi mathvariant="normal">.</mi><mi>t</mi><mi>e</mi><mi>x</mi><mi>t</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">(&quot;div&quot;).text(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord">&quot;</span><span class="mord mathnormal">d</span><span class="mord mathnormal">i</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mord">&quot;</span><span class="mclose">)</span><span class="mord">.</span><span class="mord mathnormal">t</span><span class="mord mathnormal">e</span><span class="mord mathnormal">x</span><span class="mord mathnormal">t</span><span class="mopen">(</span></span></span></span>(this).text())
            });
        });
    });
</script>

`

Output: