Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What is the use of .each() function in jQuery ?

  • Last Updated : 01 Jul, 2021

The each() function in jQuery iterate through both objects and arrays. Arrays that have length property are traversed from the index 0 to length-1 and whereas arrays like objects are traversed via their properties names.

Syntax:

$.each('array or object', function(index, value){
  // Your code
})

In this .each() function, an array or an object is given as the first argument and a callback function. This callback function optionally takes two parameters that are index and value. Therefore, we have to pass a callback function to each() method.

Example 1:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <!-- using jquery library -->
    <script src=
    </script>
</head>
  
<body>
  <script>
    let arr = [10, 20, 30, 40, 50];
    $.each(arr, function (index, value) {
        document.write(index + ": " + value + "<br>");
    });
  </script>
</body>
  
</html>

 



Output:

$(selector).each(): We can also break the loop early by returning false from the callback function. It is the same as above each() function, but it iterates over the DOM elements of the JQuery object and can execute a function for every element.

Syntax:

$('selector').each(function(index, value){
    // Your code
})

It only accepts a callback function that executes for each selected element.

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <!-- using jquery library -->
    <script src=
    </script>
</head>
  
<body>
    <p>para-1</p>
    <p>para-2</p>
    <p>para-3</p>
    <p>para-4</p>
    <p>para-5</p>
    <script>
        $("p").each(function (index) {
            console.log(index 
                + ": " + $(this).text());
        });
    </script>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!