What is each method in jQuery

The jQuery provides two types of each() functions to loop through elements or arrays.

See an example of Each with selector

This can be quite useful in scenarios e.g. you want to apply some settings/effects in different DOM elements like links, paragraphs etc. by some user’s preference or actions.

An example with an array

This chapter will describe both.

How to use the jQuery $(selector).each method

Following is the syntax of jQuery each method with selector:

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

This method is used to loop through specified elements of DOM. A function will run for each matched element. This is very useful for documents with multiple elements manipulation.

The each method index starts from 0. You have to specify Selector in that ‘each’ method.

An ‘each’ method example with selector

The example below shows how a loop works for jQuery $(selector).each method. We have three paragraphs (p) in a Div.

The $(selector).each jQuery method finds all <p> (paragraphs) and iterates through till it ends. We have a variable i that increments by 1 after each iteration and shows its value in an alert box, along with changing the background color of the paragraph.

The each function is called in the context of the current specified element so the keyword this” refers to that element. Click demo link below to see the example online.

Experience this example online

The .each() VS $(selector).each method

The $.each() method is used to loop through objects and arrays. The $(selector).each is different to $.each in that the former is exclusive to jQuery object. While the $.each() can be used to loop through any collection like jQuery arrays.

Syntax of simple each method

Following is the syntax of “each” method (without selector):

$.each( collection_Array, function(index, value) )

Example of using $.each() with a numeric array

The example below will run through a numeric array using jQuery $.each method. The alert box will show the index of the array along with the value of the element. The each works like the foreach in programming languages to run through each element of an array.

The each array index starts from 0.

Experience this example online

An example of each with break

You can also break the ‘each’ loop just like in other programming languages. In order to “each and break” work, simply make the callback function false.

Following example is the duplication of above example except we placed a condition (as array reaches 30) where the function will return as false, that will break the ‘each’ and stop the iteration. See example online:

Experience this example online

As you can see, rather going to the 5th element, as the array element value reached 30 the each method exited.

Also see: jQuery array