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.
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.
Let's see some illustrations to understand the each() method clearly.
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.
OutputTest it Now
After the execution of the above code, the output will be -
On clicking the button, an alert will be displayed as follows.
Similarly, four alert boxes will be displayed because of four li elements.
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.
OutputTest it Now
After the execution of the above code, and clicking the given button, the output will be -