jQuery each() method

The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.

The each() accepts a parameter function(index,element) which is a callback function that executes for each selected element. This function further optionally requires two parameters that are index and element. So, we have to pass a callback function to the each() method.

We can also return false from the callback function to stop the loop early.

Syntax

Parameter values

The parameter values used in each() method are defined as follows.

function(index,element): It is a mandatory parameter. It is a callback function that executes for every selected element. It has two parameter values that are defined as follows.

  • index: It is an integer value that specifies the index position of the selector.
  • element: It is the current element. We can use this keyword to refer the currently matched element.

Let's see some illustrations to understand the each() method clearly.

Example1

In this example, the each() method will be triggered on clicking the button. We are applying this method to the li elements. So, this method will iterate over each li element. The function is executed for each selected li and displays the text of the corresponding li element using alert box.

Here, we are not using the parameter values of the callback function.

Output

Test it Now

After the execution of the above code, the output will be -

jQuery each() method

On clicking the button, an alert will be displayed as follows.

jQuery each() method

Similarly, four alert boxes will be displayed because of four li elements.

Example2

In this example, we are using the parameter values of the callback function that are index and element.

We are applying the each() method on li elements. So, the method will iterate over the li elements starting from index 0. It will execute on each selected li element and change the background color of the corresponding element.

The iteration stops once the function returns false. Here, there are six li elements, and the function stops when it reaches to the element with id = "i4". Although it is the fourth element, but the index starts at 0, so the position of the element is 3.

Output

Test it Now

After the execution of the above code, and clicking the given button, the output will be -

jQuery each() method




Latest Courses