jQuery.each() funciton example

One of the most widely used jQuery function is jQuery.each() function. It can be used for both jQuery and non jQuery objects/collection. For non jQuery object or collection the syntax is $.each(object, callback-function) and for jQuery objects the syntax is object.each(function)

Writing each function on non-jQuery objects:

Array example

<script language="javascript"> var ary = ["JavaScript", "JQuery", "HTML", "Asp.net", "SQL"]; $(document).ready(function () { $.each(ary, function (index, value) { document.write(index + ". " + value + "<br/>"); }); }); </script>

Output :

JSON example

<script language="javascript"> var jsonObj = { "Employee Name": "Steave", "Salary": 15000, "DOB": "04/05/1985", "DOJ": "08/02/2013" }; $(document).ready(function () { $.each(jsonObj, function (key, value) { document.write(key + " : " + value + "<br/>"); }); }); </script>

Output :

Writing each function on jQuery objects

HTML controls collection example

in this example we will take a list item collection and we will add brackets ([ ]) to each item.

<ul> <li>JavaScript</li> <li>JQuery</li> <li>Asp.net</li> <li>HTML</li> </ul> <script language="javascript"> $(document).ready(function () { $("li").each(function () { $(this).text("[" + $(this).text() + "]"); }); }); </script>

Output :

  • JavaScript
  • JQuery
  • Asp.net
  • HTML

Note : Some time it is not necessary to use the each function, some inbuilt jQuery function will automatically do the each loop on the selected collection.
Ex : In the above HTML controls collection example for adding bracket to the value we need to use the .each() function. but for adding a new class to each list item no need to write the each funtion, we can directly use the inbuilt addClass() function.

$("li").text("[" + $("li").text() + "]"); -> this will not work, need to write each function

$("li").addClass("newcssclass"); ->this will work, no need to write each function in this scenario.