jQuery Each Function Example

Let's have a closer look at the jQuery .each() function.

Demo Code Download

Description

There are two versions of the each method in jQuery - $.each() uses the jQuery namespace and .each() acts directly upon targeted DOM elements. I am a big fan of shorthand techniques and jQuery provides us with a fast alternative to basic JavaScript loops. You can use $.each() and .each() on lots of different things such as DOM Elements, Arrays, Objects, JSON etc. I have 5 more jQuery.each() examples to show you! Lets have a look at an example of the each jQuery function in action. Further Reading »

Demo

jQuery Function Demo - jQuery4u.com

Demo 1: Using $.each() to loop through values in an array.

Output an array containing the countries of the world.

Run Demo View Code

Demo 2: Using .each() to loop through DOM elements.

This demo loops through all the h2 tags on this web page and created a table of contents.

Run Demo View Code


    Download

    The download package includes all the inline HTML, CSS, JavaScript, jQuery and images required for the .each() function demo so you can try it yourself and change as you please.

    The full code listing for all jQuery functions have been now added to GitHub, you can get them there, we are making them work with the latest versions of jQuery!

    Code

    <!-- Copyright 2011 jQuery4u.com -->
    <!DOCTYPE html>
    <html>
    <title>jQuery Function Demo - jQuery4u.com</title>
    <head>
        <script src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
        <script src="http://www.jquery4u.com/scripts/function-demos-script.js"></script>
    
        <script type="text/javascript">
    
        var JQFUNCS =
        {
            runFunc:
            {
                /* ------------------------------ Each Demo 1 ------------------------------ */
                "each1":
                {
                    run: function(id)
                    {
                        var demobox = $('#'+id);
                        var countryArray = ["Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antarctica","Antigua and Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Bouvet Island","Brazil","British Indian Ocean Territory","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Côte d'Ivoire","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Christmas Island","Cocos (Keeling) Islands","Colombia","Comoros","Congo","Cook Islands","Costa Rica","Croatia","Cuba","Cyprus","Czech Republic","Democratic Republic of the Congo","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Faeroe Islands","Falkland Islands","Fiji","Finland","Former Yugoslav Republic of Macedonia","France","French Guiana","French Polynesia","French Southern Territories","Gabon","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guadeloupe","Guam","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Heard Island and McDonald Islands","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Martinique","Mauritania","Mauritius","Mayotte","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Niue","Norfolk Island","North Korea","Northern Marianas","Norway","Oman","Pakistan","Palau","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Pitcairn Islands","Poland","Portugal","Puerto Rico","Qatar","Réunion","Romania","Russia","Rwanda","São Tomé and Príncipe","Saint Helena","Saint Kitts and Nevis","Saint Lucia","Saint Pierre and Miquelon","Saint Vincent and the Grenadines","Samoa","San Marino","Saudi Arabia","Senegal","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Georgia and the South Sandwich Islands","South Korea","Spain","Sri Lanka","Sudan","Suriname","Svalbard and Jan Mayen","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","The Bahamas","The Gambia","Togo","Tokelau","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Turks and Caicos Islands","Tuvalu","US Virgin Islands","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","United States Minor Outlying Islands","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Wallis and Futuna","Western Sahara","Yemen","Yugoslavia","Zambia","Zimbabwe"]
                        var len = countryArray.length;
                        $.each(countryArray , function(index, value){
                            demobox.append(index+1 + '. ' + value);
                            if (!(index == len - 1))
                            {
                                 demobox.append(', ');
                            }
                            else
                            {
                                demobox.append('.');
                            }
                        });
                    },
    
                    reset: function(id)
                    {
                        $('#'+id).empty().hide();
                    }
                },
    
                /* ------------------------------ Each Demo 2 ------------------------------ */
                "each2":
                {
                    run: function(id)
                    {
                        var demoboxList = $('#'+id+' ol');
                        $("h2").each(function(i) {
                            var curr = $(this);
                            curr.attr("id", "title" + i);
                            demoboxList.append("<li style='margin:0;padding:0'>"+curr.html() + "</a></li>");
                        });
                    },
    
                    reset: function(id)
                    {
                        $('#'+id).html('<ol></ol>').hide();
                    }
                }
            }
        }
    
        </script>
    
    </head>
    <body>
    
    <h3>Demo 1: Using $.each() to loop through values in an array.</h3>
    <p>Output an array containing the countries of the world.</p>
    <p><a href="#" id="each1-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="each1-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="each1-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
    <div class="demoarea" id="each1"></div>
    
    <h3>Demo 2: Using .each() to loop through DOM elements.</h3>
    <p>This demo loops through all the h2 tags on this web page and created a table of contents.</p>
    <p><a href="#" id="each2-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="each2-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="each2-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
    <div class="demoarea" id="each2"><ol></ol></div>
    
    </body>
    </html>
    <!-- Copyright 2011 jQuery4u.com -->