jQuery Foreach Example – jQuery .each() Example

In  jQuery Foreach Example, I have explained how to loop through an array / object / DOM element list using jQuery .each() function.

Below are the examples covered.
1) jQuery .each() syntax
2) loop through an array
3) loop through an object
4) loop through DOM Element List

[demo title1=”jQuery Foreach Example using .each() function” url1=”http://hayageek.com/examples/jquery/foreach/index.php”%5D

1).jQuery .each() syntax

To loop through an array or object we can use below syntax

jQuery.each( array, callback )
$.each( array, callback )

for arrays callback type is: Function(index,eachObject)

for objects callback type is : Function(properityName,object)


To loop through DOM List we can use the below syntax


//where callback type: Function(integer,element)

Note: Actually jQuery.each() ,$(selector).each() are two different functions

2). Loop through an Array – jQuery Foreach Example

You can use the below code to loop through an array/ JSON array. Inside the callback function, we can use this keyword also to access the object.

//Example: 1
var arr =[1,2,4,5,6];
    //We can access the object using obj or this
    alert("index:"+index + " , value: "+obj +" , value:"+this);

//Example: 2 (JSON Array)
var arr2 =[{
                loc:"United States"
    alert("Name: "+obj.name+"\n"+"Age:"+obj.age+"\n"+"Location: "+obj.loc+"\n");

[demo title1=”jQuery Foreach JSON Array” url1=”http://hayageek.com/examples/jquery/foreach/index.php#two”%5D

3). Loop through an Object  РjQuery Foreach Example

var obj = { name: "ravi", age: 33, loc: "India", gender: function() { return "M"} }
    alert("prop:"+prop + " , value: "+obj);

    if($.type(obj) == "function")
        alert(" gender:" + obj());  //we can call the function also

Note: We can even access the functions and call them using object.
[demo title1=”jQuery Foreach Object” url1=”http://hayageek.com/examples/jquery/foreach/index.php#three”%5D

4). Loop through DOM Elements using jQuery $.each() example

//To Loop through all the links in page : <a href=""></a>
    alert($(obj).attr("href")+"  "+$(this).html());

//To loop through all the elements with tag <input> 

//To loop through all the element with class name "myClass"

[demo title1=”jQuery Foreach DOM Elements” url1=”http://hayageek.com/examples/jquery/foreach/index.php#four”%5D
Reference: jQuery Documentation