How to use each() in jQuery With Example

In this post, we are going to discuss about jQuery each() method, which is one of the most important and mostly used traversing functions in jQuery.

jQuery each()

This method lets you to iterate over the DOM elements of the jQuery object and executes a function for each matched element.
You have to pass a callback function to each() method which is executed for each selected element. The call back function is triggered in the context of the current DOM element, so you can use this keyword to refer the currently matched element. You can return false from the callback function to stop the loop early.

Here is the general syntax for using jQuery each() method:

function is the call back method triggered for each matched element.This is a mandatory parameter for the each() method. function(index,element) takes two parameters , index and element.
index an integer value, which is the index of the selected element.
element is the selected element itself.

jQuery each() example

Following example demonstrates the jQuery each() usage.

In this example, the each() is triggered on clicking the button. The each() takes a function(index, element) as an argument. The each() iterates over the selected div elements starting from the first index, that is from index 0. The function is executed for each selected div and changes the CSS style of the currently matched div.

This iteration stops when the function returns false. Here, is() method checks for an “id=stop” and the passed function returns false when the index is 4, which in turn stops the iteration.

You can click on below button to try it out yourself.

I hope the jQuery each() usage is clear now. That’s all for now. We will discuss some more traversing techniques in the coming posts.

By admin

Leave a Reply

%d bloggers like this: