JQuery each() method

each() method in jquery is used to iterate an array of elements or numbers. This can also be used to iterate array of objects.

jquery-each-method

Parameters:

  • index: index of element or object in array.
  • value: value of element or object in array.
  • array: contains elements or objects.

Example:


$(".ele").each(function(index, value){
    console.log("element at "+ (index)+ " position is " + value);
});

In above example, there are some div’s with class name “ele”. We can iterate all div’s with class “ele” using each method.

Alternative syntax:

jquery-each-syntax

Iterating array of objects.
Consider an example of a employee object.

var employee={
      "name": "John",
      "age":23,
     "designation":"software engineer"
}

Now, we are creating employee’s array which contains of all employee objects.

var employees=[
  {
      "name": "John",
      "age":23,
     "designation":"software engineer"
  },
  {
      "name": "Michel",
      "age":32,
      "designation":"Finance manager"
  },
  {
      "name": "Xira",
      "age":28,
      "designation":"HR recruiter"
  }
]

Now apply $.each method to iterate employees array to get each employee info.

$.each(employees,function(index,value){
   console.log("Name: " + value.name)
   console.log("Age: "+value.age)
   console.log("Designation: " + value.designation);
});

Above example will return information of each employee.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>