Skip to content

JQuery Foreach Example

Foreach provides easy way to iterate over the arrays, objects. Foreach is the most important control structure in any language. So i am going to write a simple comprehensive tutorial on JQuery’s $.each() function.I would like to show you example on how to loop through an array ,object,JSON and DOM elements.

jQuery.each() syntax

jQuery.each( array, callback )

//or
$.each( array, callback )

// with callback
jQuery.each( array, function(index,value){

});

jQuery.each() Array Example

var numberArray = [0,1,2,3,4,5];
jQuery.each(numberArray , function(index, value){
     console.log(index + ':' + value);
});
//outputs: 1:1 2:2 3:3 4:4 5:5

jQuery.each() Object Example

(function($) {
var json = [
    { "name": "Arjun" },
    { "name": "Pravinh" },
    { "name": "Jack" }
];
 
$.each(json, function() {
  $.each(this, function(name, value) {
    /// do stuff
    console.log(name + '=' + value);
  });
});
})(jQuery);

//outputs: 
//  name=Arjun 
//  name=Pravinh 
 // blue=Jack

jQuery.each() DOM Example

For example, given the following markup:


.each() may be used like so:

$( "li" ).each( function( index, element ){
    console.log( $( this ).text() );
});
 
// Logs the following:
// Link 1
// Link 2
// Link 3
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments