The jQuery each() method can be used to iterate through a jQuery object. You can find each element content using the method. It performs the iterations according to the number of items the selected element contains.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and iterate through each matching element. You can use the element tag name, class name, or id to select. It is a required field. |
function | It is used to run iteration over the matching content.
|
jQuery each() Method to Iterate Over jQuery Object
If you want to iterate through the items of the matching element, you have to use the method as given below. The example contains the div element and the paragraph items inside it. You have to iterate through the items to get the text content.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("div p").each(function(index){ alert($(this).text()); }); }); }); </script> <div> <p>First item.</p> <p>Second item.</p> <p>Third item.</p> </div> <button type="button" class="mybtn">Click to Iterate</button> |
Output
First item.
Second item.
Third item.
Click the button to get the text content of each element inside the div. You will get the text content in an alert box for each item. The iteration will be performed three times as there are three items in the div element.
Iterate Through List Element Items to Get Class
If you want to get the class of each item of list element, you have to use the example as given below. It finds the class of list items and displays in the alert box. You can also join these classes to create an array object.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('.myulbtn').click(function(){ $("ul li").each(function(index){ alert($(this).attr('class')); }); }); }); </script> <ul> <li class="one">1st element.</li> <li class="two">2nd element.</li> <li class="three">3rd element.</li> </ul> <button type="button" class="myulbtn">Click to Iterate</button> |
Output
- 1st element.
- 2nd element.
- 3rd element.
When you click the button given above, it displays the class of each list item in the alert box. The jQuery each() method performs iteration three times as there are three list items.
You may also like to read
I hope you like this tutorial on jQuery each() method. If you have any queries regarding the tutorial, please comment below.
References