Friday, November 21, 2008

jQuery Array Iteration – $.each

jQuery $.each can be used in order to iterate over an array:

$(document).ready(function() {
    var arr = [ "a", "b", "c", "d", "e" ];
    
    $.each(arr,function(index, item)
    {
        $('#list').append($( "<li>" + item + " at " + index +"</li>" ));
    });
    
});

You should have a <ul> with id=list for this code to work:

<ul id="list">
    <!--the items will be added here -->
</ul>

The result is:

image

Here is the entire code:

<html>
<head>
    <title>jQuery Array Iteration</title>
 
    <script src="scripts/jquery/jquery-1.2.6.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
        $(document).ready(function() {
            var arr = [ "a", "b", "c", "d", "e" ];
            
            $.each(arr,function(index, item)
            {
                $('#list').append($( "<li>" + item + " at " + index +"</li>" ));
            });
            
        });
 
    </script>
</head>
<body>
     
    <ul id="list">
            <!--the items will be added here -->
    </ul>
 
</body>
</html>

Important to note that this is not the same as $(‘DOMElement’).each().

 

Source

No comments:

Post a Comment