top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of jquery .each() function?

+2 votes
105 views
What is the use of jquery .each() function?
posted Jul 8, 2015 by Shivaranjini

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

There are two types of jQuery's each, the one iterates over and returns jQuery objects, the other is a more generic version.

Core/each
Example: Create a csv of all the hrefs on the page. (iterates over matching DOM elements and 'this' reffers to the current element)
var hrefs = "";

 $("a").each(function() { 
     var href = $(this).attr('href');
     if (href != undefined && href != "") {
         hrefs = hrefs + (hrefs.length > 0 ? "," + href : href);
     }
 });

 alert(hrefs);

Utilities/jQuery.each
Iterating over an array or the elements of an object:

$.each( { name: "John", lang: "JS" }, function(i, n){
  alert( "Name: " + i + ", Value: " + n );
});

$.each( [0,1,2], function(i, n){
  alert( "Item #" + i + ": " + n );
});
answer Jul 8, 2015 by Vrije Mani Upadhyay
...