# How to use jQuery.each

In this short tutorial, we’ll show you how to iterate through a group of elements and perform actions using jQuery.each().

## What is jQuery.each()?

JQuery.each() is a method from the JavaScript library jQuery. It’s used to **iterate over a collection of elements**, such as arrays or objects, and perform certain actions. This makes .each() very useful for manipulating the [Document Object Model (DOM)](https://www.ionos.ca/digitalguide/websites/web-development/an-introduction-to-the-document-object-model-dom/ "An introduction to the Document Object Model (DOM)"), which is an interface between HTML and JavaScript. In our [jQuery-tutorial](https://www.ionos.ca/digitalguide/websites/web-development/jquery-tutorial-introduction-and-first-steps/ "jQuery tutorial: introduction and first steps"), you can learn how to embed the popular library.

## What is the syntax for jQuery.each()?

With .each(), every element in a collection is iterated and one function is executed per iteration. There are two kinds of .each(). The basic syntax looks like this:

```jQuery
$.each(object, callback)
```

Here, “object” is an array or object, and “callback” is the function that is called in each pass. Its parameters consist of the **index or element key and the element itself**. The indexing of the elements in an array starts at 0.

In the next example, all elements in the “arr” array are executed. In each iteration, the index and the value are output to the console.

```jQuery
var arr = ["blue", "yellow", "red"];
$.each(arr, function(index, value) {
    console.log(index + ": " + value);
});
```jQuery
The output looks like this:
```jQuery
0: blue
1: yellow
2: red
```

To select DOM elements, use .each() with [jQuery selectors](https://www.ionos.ca/digitalguide/websites/web-development/jquery-selectors/):

```jQuery
$(selector).each()
```

Next, all list elements from the unsorted “alphabet” list are selected and their position as well as their content are displayed via the console. The **keyword “this”** refers to the element.

```jQuery
<ul id="alphabet">
    <li>a</li>
    <li>b</li>
    <li>c</li>
</ul>
```

```jQuery
$("li").each(function(index) {
    console.log( index + ": " + $(this).text() );
});
```

The output looks like this:

```jQuery
0: a
1: b
2: c
```

## jQuery.each() examples

jQuery.each() can be used to perform complex DOM manipulations.

Note Since some jQuery methods also iterate over all elements of a collection, it may make sense to use an implicit iteration instead of .each() in some cases.

To add the same class name to all div elements, you can use the function [.addClass()](https://www.ionos.ca/digitalguide/websites/web-development/jquery-addclass/) in combination with .each():

```jQuery
<div class="header"></div>
<div class="main"></div>
<div class="footer"></div>
```

```jQuery
$("div").each(function() {
    $(this).addClass("container");
});
```

The output looks like this:

```jQuery
<div class="header container"></div>
<div class="main container"></div>
<div class="footer container"></div>
```

The same code can be shortened by implicit iteration:

```jQuery
$("div").addClass("container");
```

.each() is especially useful for JavaScript events. In the next example, a click event changes the color of the div elements. Optionally, the **code can be directly embedded in the script tag of the HTML document**. Initially, the color of the containers is set to “green”. When a click happens in the document, the condition is evaluated, and the color value changes to “red”. With another click, the property “color” is assigned back to the default “green” value again.

```jQuery
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
    <style>
    div {
        color: green;
        text-align: center;
        cursor: pointer;
        width: 300px;
    }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div>Click here</div>
<div>to change</div>
<div>the color.</div>
<script>
$(document.body).click(function() {
    $("div").each(function(i) {
        if (this.style.color !== "red") {
            this.style.color = "red";
        } else {
            this.style.color = "";
        }
    });
});
</script>
<div class="hash d-none" hidden>hash_7df483a98a4f9086f60260a89e0fd4f705559774</div><script data-shy-copy-guard>(function(){var C=[0x00AD,0x200B,0x200C,0x200D,0x2060,0xFEFF];var s=function(t){for(var i=0;i<C.length;i++){t=t.split(String.fromCharCode(C[i])).join("");}return t;};document.addEventListener("copy",function(e){var sel=document.getSelection();if(!sel||sel.isCollapsed||!e.clipboardData){return;}e.clipboardData.setData("text/plain",s(sel.toString()));try{var d=document.createElement("div");d.appendChild(sel.getRangeAt(0).cloneContents());e.clipboardData.setData("text/html",s(d.innerHTML));}catch(x){}e.preventDefault();});})();</script></body>
</html>
```

In addition, you can use jQuery.each() to create transitions or animations. In this example, the elements in the “numbers” list receive a blue background color on a click event and are then faded out one after the other according to an index-based time interval.

```jQuery
<ul id="numbers">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
```

```jQuery
$("#numbers").on("click", function(e) {
    $("li").each(function(index) {
        $(this).css("background-color", "blue")
                     .delay(index * 300)
                     .fadeOut(2000);
    });
    e.preventDefault();
});
```


This is a markdown version of: [https://www.ionos.ca/digitalguide/websites/web-development/jquery-each/](https://www.ionos.ca/digitalguide/websites/web-development/jquery-each/) for AI/LLM consumption.