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), which is an interface between HTML and JavaScript. In our jQuery-tutorial, 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:

$.each(object, callback)
jQuery

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.

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
jQuery

To select DOM elements, use .each() with jQuery selectors:

$(selector).each()
jQuery

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.

<ul id="alphabet">
    <li>a</li>
    <li>b</li>
    <li>c</li>
</ul>
jQuery
$("li").each(function(index) {
    console.log( index + ": " + $(this).text() );
});
jQuery

The output looks like this:

0: a
1: b
2: c
jQuery

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() in combination with .each():

<div class="header"></div>
<div class="main"></div>
<div class="footer"></div>
jQuery
$("div").each(function() {
    $(this).addClass("container");
});
jQuery

The output looks like this:

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

The same code can be shortened by implicit iteration:

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

.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.

<!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>
</body>
</html>
jQuery

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.

<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();
});
jQuery
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.