5 Examples of the jQuery.each() Function

Main Points

  • The jQuery.each() method can be used to iterate over DOM elements, arrays, and objects. This makes it easy to work with and process data that has multiple elements.
  • The function can be used in two different ways: as a method on a jQuery object for DOM elements or as a utility function for arrays and objects. Each way works with a different kind of data structure.
  • The article uses real-life examples to show how powerful and flexible jQuery.each() is. It stresses how important it is for making the iteration process easier and shows other JavaScript methods that can be used for similar tasks.

What does jQuery do?

jQuery’s each() function is used to go through each element of the target jQuery object. This is an object that has one or more DOM elements and all of jQuery’s methods available. It’s great for working with the DOM that has more than one element and for iterating over any arrays and object features.

Besides this function, jQuery also has a helper function with the same name that can be called even if no DOM elements have been chosen or made yet.

1. jQuery.each() Code Example

Let’s check out how the different modes work.

In the code below, every

element on an online page is chosen, and its index and ID are printed.

What could happen is this:

// DOM ELEMENTS
$('div').each(function(index, value) {
  console.log(`div${index}: ${this.id}`);
});

The utility function is not used in this version; instead, the $(selector).each() method is used.

The next case shows how the utility function can be used. The object to loop over is given as the first input in this case. We’ll show you how to loop over a list in this case:

div0:header
div1:main
div2:footer

In the last example, we’ll show you how to go through an object’s features one by one:

// ARRAYS
const arr = [
  'one',
  'two',
  'three',
  'four',
  'five'
];

$.each(arr, function(index, value) {
  console.log(value);
  // Will stop running after "three"
  return (value !== 'three');
});

// Outputs: one two three

It all comes down to giving a good callback. This, the context of the callback, will be the same as its second input, which is the last value. However, since the context will always be an object, simple values need to be wrapped like this:

// OBJECTS
const obj = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5
};

$.each(obj, function(key, value) {
  console.log(value);
});

// Outputs: 1 2 3 4 5

In other words, the value and the situation are not strictly equal.

1. Basic jQuery.each() Function Example

We will look at how the jQuery.each() function works with a jQuery object. In the first case, the href attribute of all the an elements on the page is shown:

$.each({ one: 1, two: 2 } , function(key, value) {
  console.log(this);
});

// Number { 1 }
// Number { 2 }

If you only use HTTP(S), the second example shows all of the foreign links on the web page:

$.each({ one: 1 } , function(key, value) {
console.log(this == value);
console.log(this === value);
});

// true
// false



Let's say the page had these links:

This is what the second case would show:

https://www.sitepoint.com/
https://developer.mozilla.org/
http://example.com/



It is important to remember that DOM parts from a jQuery object are in their "native" form in the callback that was sent to jQuery.each(). The reason for this is that jQuery is just a container for a list of DOM objects. jQuery.each() is used to run through this array like it would be any other array. Because of this, we don't get wrapped parts right out of the box.

This means that we can write this.href to get an element’s href property, which is what our second example shows. To use the attr() method in jQuery, we would have to re-wrap the element like this: $(this).attr(‘href’).

2. An Example of jQuery.each() Array

Let’s take a look at how to deal with a normal array again:

const numbers = [1, 2, 3, 4, 5];
$.each(numbers, function(index, value){
  console.log(`${index}: ${value}`);
});

This piece of code prints:

0:1
1:2
2:3
3:4
4:5

Not much going on here. There are numeric indices in an array, so we get numbers from 0 to N-1, where N is the number of items in the array.

3. An Example of jQuery.each() JSON

Other types of data structures could be arrays inside arrays, objects inside objects, arrays inside objects, or objects inside arrays. Let us look at how jQuery.each() can help us here:

const colors = [
  { 'red': '#f00' },
  { 'green': '#0f0' },
  { 'blue': '#00f' }
];

$.each(colors, function() {
  $.each(this, function(name, value) {
    console.log(`${name} = ${value}`);
  });
});

This example gives you:

red = #f00
green = #0f0
blue = #00f

The stacked structure is taken care of by calling jQuery.each() inside another call to it. The collection of variable colours is handled by the outer call, and each object is handled by the inner call. In this case, each object only has one key, but this code could be used to deal with any amount.

4. An Example of the jQuery.each() Class

This example shows how to use a loop to go through each element and give a class product to each one.This is what the HTML below says about it:

<div class="productDescription">Red</div>
<div>Pink</div>
<div class="productDescription">Orange</div>
<div class="generalDescription">Teal</div>
<div class="productDescription">Green</div>

The each() method on the selection is not used; instead, the each() helper is used.

What comes out in this case is:

$.each($('.productDescription'), function(index, value) {
  console.log(index + ':' + $(value).text());
});


We don’t need to add value and index. These are just parameters that help us figure out which DOM part we’re iterating over at the moment. In this case, we can also use the way that is most convenient for us. This is how we can write it:

0:Red
1:Orange
2:Green

This is what we’ll get on the console:

$('.productDescription').each(function() {
  console.log($(this).text());
});


That’s why we’re enclosing the DOM element in a new jQuery instance: we can use jQuery’s text() method to get the text inside the element.

Red
Orange
Green

5. An Example of jQuery.each() Delay

All of the things in the next list will turn orange as soon as the user clicks on the element with the ID 5demo.

<ul id="5demo">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>

In milliseconds, we fade out the part after a delay that depends on the index (0, 200, 400, etc.).

$('#5demo').on('click', function(e) {
  $('li').each(function(index) {
    $(this).css('background-color', 'orange')
           .delay(index * 200)
           .fadeOut(1500);
  });

  e.preventDefault();
});

In conclusion

We showed you how to use the jQuery.each() function to go through DOM items, arrays, and objects one by one in this post. Developers should have this handy little function in their toolboxes because it’s useful and saves time.

And if you don’t like jQuery, you could use the Object.keys() and Array.prototype.forEach() tools that come with JavaScript. And there are tools, like foreach, that let you go through the key-value pairs of either an array or a dictionary.

Remember: $.each() and $(selector).Each() and each() are two different methods that are set up in two different ways.

This well-known article was updated in 2020 to include the latest best practices and to improve the tips at the end about using modern JavaScript for native solutions. Read our book, JavaScript: Novice to Ninja, 2nd Edition, to learn more about the language in depth.

FAQs about the each() function in jQuery

What is the point of jQuery’s.each() function?

jQuery’s.each() method is used to go through a list of DOM elements one by one and do a certain action on each one.

In jQuery, how do I use the.each() event?

To use the.each() method, use a jQuery selector to pick out a group of elements, then call.each() on that group. You give it a callback code that tells it what to do with each element.

What are the arguments of the function that is called when.each() is used?

The callback method takes two arguments: index, which is the current index of the element in the collection, and element, which is the DOM element that is being iterated over at the moment.

Can you tell me how to use the index argument in the.each() callback function?

The index parameter lets you keep track of where the current element is in the collection. This can help you with other processes or actions that depend on other elements.

What are some popular ways to use the.each() function?

Iterating through a list of elements to change their traits, values, or styles is a common use case, as is doing custom actions on each element in a collection.

Author photo
Publication date: