DEV Community

Udoka Emmanuel
Udoka Emmanuel

Posted on

## Understanding jQuery.each(): A Friendly Guide

Hey there! Let's dive into the world of jQuery and explore the jQuery.each() function. It's a nifty tool for looping through elements, arrays, and object properties. Whether you're a beginner or looking to brush up on your jQuery skills, this guide is here to help you out!

What is jQuery.each()?

The jQuery.each() function is your go-to for looping through elements in a jQuery object. This object can contain one or more DOM elements, and it lets you perform all kinds of jQuery magic on them. It's super handy for manipulating multiple elements or iterating over arrays and object properties.

But wait, there's more! jQuery also offers a helper function named each() that you can use without needing to select or create any DOM elements first.

Syntax of jQuery.each()

Let's check out how this function works. We'll start with some basic examples to get you comfortable.

Looping Through DOM Elements

Suppose you want to loop through every <div> element on your web page and log their indices and IDs:

$('div').each(function(index) {
  console.log(`div${index}: ${this.id}`);
});
Enter fullscreen mode Exit fullscreen mode

If your HTML has the following <div> elements:

<div id="header"></div>
<div id="main"></div>
<div id="footer"></div>
Enter fullscreen mode Exit fullscreen mode

The output will be:

div0: header
div1: main
div2: footer
Enter fullscreen mode Exit fullscreen mode

Using the Utility Function

Now, let's see how you can use the utility function to loop over an array:

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

$.each(arr, function(index, value) {
  console.log(value);
  // Stops running after "three"
  return (value !== 'three');
});
Enter fullscreen mode Exit fullscreen mode

This will log:

one
two
three
Enter fullscreen mode Exit fullscreen mode

And here's how you can iterate over an object's properties:

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

$.each(obj, function(key, value) {
  console.log(value);
});
Enter fullscreen mode Exit fullscreen mode

The output will be:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Basic jQuery.each() Function Examples

Let's see how the jQuery.each() function can be useful with jQuery objects. For example, if you want to output the href attribute of every <a> element on your page:

$('a').each(function() {
  console.log(this.href);
});
Enter fullscreen mode Exit fullscreen mode

Or, if you want to log only the external links:

$('a').each(function() {
  const link = this.href;

  if (link.match(/https?:\/\//)) {
    console.log(link);
  }
});
Enter fullscreen mode Exit fullscreen mode

Given the following links:

<a href="https://www.sitepoint.com/">SitePoint</a>
<a href="https://developer.mozilla.org">MDN web docs</a>
<a href="http://example.com/">Example Domain</a>
Enter fullscreen mode Exit fullscreen mode

The output will be:

https://www.sitepoint.com/
https://developer.mozilla.org/
http://example.com/
Enter fullscreen mode Exit fullscreen mode

jQuery.each() with Arrays

Let's loop through a simple array:

const numbers = [1, 2, 3, 4, 5];

$.each(numbers, function(index, value) {
  console.log(`${index}: ${value}`);
});
Enter fullscreen mode Exit fullscreen mode

This will log:

0: 1
1: 2
2: 3
3: 4
4: 5
Enter fullscreen mode Exit fullscreen mode

Handling Complex Data Structures

What if you have an array of objects? No problem!

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

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

The output will be:

red = #f00
green = #0f0
blue = #00f
Enter fullscreen mode Exit fullscreen mode

jQuery.each() with Classes

Want to loop through elements with a specific class? Easy!

Given this HTML:

<div class="productDescription">Red</div>
<div>Pink</div>
<div class="productDescription">Orange</div>
<div class="generalDescription">Teal</div>
<div class="productDescription">Green</div>
Enter fullscreen mode Exit fullscreen mode

You can loop through the elements with the class productDescription:

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

The output will be:

0: Red
1: Orange
2: Green
Enter fullscreen mode Exit fullscreen mode

Or you can use the each method directly on the selector:

$('.productDescription').each(function() {
  console.log($(this).text());
});
Enter fullscreen mode Exit fullscreen mode

And you'll get:

Red
Orange
Green
Enter fullscreen mode Exit fullscreen mode

Adding a Delay

Want to add some flair with a delay? Let's say you want to change the background color and fade out each list item on click:

<ul id="demo">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Here's the JavaScript:

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

  e.preventDefault();
});
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

And there you have it! The jQuery.each() function is a powerful tool for looping through DOM elements, arrays, and objects. It's versatile and saves you time. Keep this in your developer toolkit, and happy coding!

Conclusion

In this guide, we've explored how to use the jQuery.each() function to iterate over DOM elements, arrays, and objects. It's a powerful and versatile function that can simplify your code and make your life easier as a developer. So next time you need to loop through elements or data structures, remember to reach for jQuery.each()!

Top comments (0)