jQuery each method


jQuery each method() uses a function to iterate for each matching element. ie. function executes for each matching element.


Syntax of jQuery each Method

$(selector).each(function(Integer index, Element element ));

Function :
Index – Current Index of selector.
element Current element.

Let us understand it very basic example :
Suppose We have following elements-


<ul>

  	<li>Item 1</li>
	<li>Item 2</li>
	<li>Item 3</li>

</ul>

Let us select all li items and iterate them-

$( "li" ).each(function( index, elem) {
  console.log( index + ": " + $( elem ).text() );
});

or

$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

The following message will be logged-

0: Item 1
1: Item 2
2: Item 3

jQuery each method Example 1

jQuery each() Method – Example

<script type="text/javascript">
         $(document).ready(function(){ 
             $( "li" ).each(function( index, elem) {
                    $("#result").append( index + ": " + $( elem ).text() );
             });     
          });
</script>

Try it »


Add Comment

📖 Read More


Advertisements