jquery
  1. jquery-each

jQuery each()

The jQuery each() function is a convenient way to iterate over a set of elements and perform a certain action on each element individually.

Syntax

The syntax for each() function is as follows:

$.each( collection, callback )

Where collection is the set of elements to iterate over (e.g. an array or object) and callback is the function to execute for each element. The callback function takes two parameters: index and value, which correspond to the current element's index and value, respectively.

Use

The each() function is useful for performing a specific action on each element in a set. It can be used in a variety of scenarios, such as iterating over a list of items, applying a function to each element in a collection, or even updating the state of multiple elements on a page.

Example

Here's an example of using the each() function to iterate over an array of names and display them in an unordered list:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

  <ul id="nameList">
    <!-- Existing list items, if any, will be preserved here -->
  </ul>

  <script>
    $(document).ready(function(){
        var names = ["Alice", "Bob", "Charlie", "David"];
        
        $.each(names, function(index, value) {
          // Append a new list item to the unordered list
          $("#nameList").append("<li>" + value + "</li>");
        });
    });
  </script>

</body>
</html>
Try Playground

In this example, we use the each() function to iterate over the names array. For each element in the array, we append a new list item to an unordered list on the page, with the element's value as the content of the list item.

Summary

The jQuery each() function is a powerful tool that allows you to iterate over a set of elements and perform a specific action on each element. Whether you're working with arrays, objects, or multiple elements on a web page, each() is a convenient and effective way to handle iteration in your code.

Published on: