jQuery -

.each()


Introduction to jQuery .each()

The jQuery .each() function is a versatile and powerful tool for iterating over arrays and objects. This utility function allows you to loop through elements in a jQuery object or items in an array or object, performing actions on each item. In this tutorial, we will cover the syntax, usage, and best practices for using .each() with detailed examples.


1. What is jQuery .each()?

The .each() method in jQuery is used to iterate over a jQuery object or a collection of DOM elements. It allows you to perform operations on each matched element, making it a powerful tool for batch processing.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>What is .each() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('div').each(function(){
                $(this).css('background-color', 'yellow');
            });
        });
    </script>
</head>
<body>
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
</body>
</html>
        
    

In this example, we demonstrate the basic usage of the .each() method by iterating over a list of DOM elements and applying a function to each.


2. Syntax of jQuery .each()

The syntax for the jQuery .each() method is as follows:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>.each() Syntax Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var array = [1, 2, 3, 4, 5];
            $.each(array, function(index, value){
                console.log("Index: " + index + ", Value: " + value);
            });
        });
    </script>
</head>
<body>
</body>
</html>
        
    

This syntax allows you to pass a callback function that will be executed for each element in the jQuery object or array.


3. Iterating Over Arrays

You can use $.each() to iterate over arrays. This is particularly useful for performing operations on each item in an array.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Iterating Over Arrays Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var numbers = [1, 2, 3, 4, 5];
            $.each(numbers, function(index, value){
                console.log(value + " squared is " + (value * value));
            });
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we iterate over an array of numbers and calculate their squares.


4. Iterating Over Objects

The $.each() function can also be used to iterate over the properties of an object.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Iterating Over Objects Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var person = {
                name: "John",
                age: 30,
                city: "New York"
            };
            $.each(person, function(key, value){
                console.log(key + ": " + value);
            });
        });
    </script>
</head>
<body>
</body>
</html>
        
    

This example demonstrates how to iterate over an object and display its properties and values.


5. Iterating Over jQuery Objects

One of the common uses of .each() is to iterate over jQuery objects, such as collections of DOM elements.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Iterating Over jQuery Objects Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('div').each(function(){
                $(this).css('background-color', 'yellow');
            });
        });
    </script>
</head>
<body>
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
</body>
</html>
        
    

In this example, we iterate over a collection of div elements and change their background color.


6. Handling Context with this Keyword

Inside the .each() method, the this keyword refers to the current element in the iteration.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Handling Context Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('div').each(function(){
                console.log($(this).text());
            });
        });
    </script>
</head>
<body>
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
</body>
</html>
        
    

This example shows how to use the this keyword to access and manipulate the current element.


7. Breaking Out of .each() Loop

You can break out of the .each() loop by returning false from the callback function.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Breaking Out of .each() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var numbers = [1, 2, 3, 4, 5];
            $.each(numbers, function(index, value){
                if (value === 3) {
                    return false;
                }
                console.log(value);
            });
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we demonstrate how to break out of the loop when a certain condition is met.


8. Nested .each() Loops

Sometimes, you may need to use nested .each() loops to perform complex operations on multi-dimensional arrays or objects.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Nested .each() Loops Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var matrix = [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]
            ];
            $.each(matrix, function(rowIndex, row){
                $.each(row, function(colIndex, value){
                    console.log("Row " + rowIndex + ", Column " + colIndex + ": " + value);
                });
            });
        });
    </script>
</head>
<body>
</body>
</html>
        
    

This example shows how to use nested .each() loops to iterate over a multi-dimensional array.


9. Best Practices for Using .each()

When using .each(), it is important to follow best practices to ensure efficient and readable code.


10. Real-World Use Cases

The .each() method is widely used in real-world applications. Here are a few scenarios where it can be particularly useful:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Real-World Use Cases Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('form').each(function(){
                $(this).find('input').each(function(){
                    if ($(this).val() === '') {
                        $(this).css('border', '1px solid red');
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form>
        <input type="text" name="name" placeholder="Name">
        <input type="text" name="email" placeholder="Email">
    </form>
    <form>
        <input type="text" name="name" placeholder="Name">
        <input type="text" name="email" placeholder="Email">
    </form>
</body>
</html>
        
    

In this example, we iterate over a form and validate its fields.


11. Combining .each() with Other jQuery Methods

You can combine the .each() method with other jQuery methods to perform more complex operations.

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Combining with Other jQuery Methods Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('div').each(function(){
                if ($(this).text().includes('special')) {
                    $(this).css('background-color', 'lightblue').addClass('highlight');
                }
            });
        });
    </script>
</head>
<body>
    <div>Normal Div 1</div>
    <div>Special Div 2</div>
    <div>Normal Div 3</div>
</body>
</html>
        
    

This example demonstrates how to combine .each() with .css() and .addClass() methods to style elements conditionally.


12. Performance Considerations

While using .each(), it is important to consider performance, especially when dealing with large datasets or complex operations.

To maintain performance:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Performance Considerations Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            // Example with a large array
            let largeArray = new Array(1000000).fill(0).map((_, i) => i);
            console.time("Filtering even numbers");
            let evenNumbers = $.grep(largeArray, function(value){
                return value % 2 === 0;
            });
            console.timeEnd("Filtering even numbers");
            console.log("Number of even numbers: " + evenNumbers.length);
        });
    </script>
</head>
<body>
</body>
</html>
        
    

In this example, we demonstrate how to optimize .each() for performance.


13. Debugging .each() Loops

Debugging .each() loops can be challenging. Here are some tips for effective debugging:

Try yourself
        
            <!DOCTYPE html>
<html>
<head>
    <title>Debugging .each() Loops Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $('div').each(function(){
                console.log("Div content: " + $(this).text());
            });
        });
    </script>
</head>
<body>
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
</body>
</html>
        
    

In this example, we use console logging to debug an .each() loop.


14. Conclusion

The jQuery .each() method is a powerful tool for iterating over arrays, objects, and jQuery objects. By following best practices and considering performance, you can effectively utilize .each() to simplify and optimize your code.