How to use .each() function with DOM element in JQuery

Introduction

$(selector).each() function execute loop over a jQuery object and executing a function for each matched element in the document.

The .each() method is designed to make looping on DOM elements. When $(selector).each() function is called on any DOM selector it iterates over all the DOM elements that matches the jQuery object. For each matching element, a callback runs.

The callback method has passed the current loop iteration index that started from 0 and the current DOM element. We can access the context of the current DOM element by using the this keyword that refers to the element.

We can also stop the iteration by making it return false.

Here is the Short Example of $(selector).each() function.
 

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://www.yourdomain.com/js/greader-json.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            var i = 2;
            $("#show").click(function () {
                $("div").each(function (index, element) {
                    $(element).css("backgroundColor", "pink");
                    if (index === 2) {
                        $("#msg").append(index);
                        return false;
                    }
                });
            });
        });

    </script>
    <style type="text/css">
        div
        {
            background: yellow;
            margin: 5px;
        }
    </style>
</head>
<body>
    <label id="show">
        Click Me</label></br>
    <div>
        First Div
    </div>
    <div>
        Second Div</div>
    <div>
        Third Div</div>
    <div>
        Forth Div</div>
    <div>
        Fifth Div</div>
    </br>
    <h4 id="msg">
        Stop at location:
    </h4>    
</body>
</html>


In the above code the iteration over the div is goes through until the index of the div is not equal to 3 (Starting from 0).

Output

each-function-in-jquery.png

Ebook Download
View all
Learn
View all