jQuery each() Method

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.

jQuery each() Method

Syntax

The syntax of this method is given below:-

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

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.

  • index: It is the index position of the element.
  • element: It is used for the current element.

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

Test it Live

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

Test it Live

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