0

I have used both ways before but I'm not sure what the differences are. Could someone explain the differences?

1. $(myObjects).each(function(){}};

2. $.each($(myObjects), function(){});
Weblurk
  • 6,562
  • 18
  • 64
  • 120
  • NO worries, this question is clear. – Shahid Karimi Mar 07 '14 at 08:22
  • Those aren't declarations. And not only has this been [asked and answered already](http://stackoverflow.com/questions/6611190/what-is-the-difference-between-eachselector-and-selector-each), but there's the documentation ([`$.each`](http://api.jquery.com/jQuery.each/), [`.each`](http://api.jquery.com/each/)) as well. – T.J. Crowder Mar 07 '14 at 08:24

3 Answers3

2

jQuery Object Iterator

$('.myClass, .anotherClass').each(function(){}};

This is to loop over each jquery element, from your selector.

From the docs:

Iterate over a jQuery object, executing a function for each matched element. The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object.

.each() docs


Generic iterator

var arr = [1,2,3,4];
$.each(arr, function(index, value){});

This is a utility method to loop over an array or an object.

From the docs:

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

$.each() docs


Difference:

You can use both: $.each() and .each() to loop over a jQuery object list.

// Can be used to iterate any list or object
var $selectedElements = $('.tabs');
$.each($selectedElements, function(index, value){
    $(this).html(index);
});

// Can only be used for iterating a list of jquery objects, 
//  and is the recommended way of doing it.
$selectedElements.each(function(index, element){
    $(this).html(index);

});

But you cannot use .each() to loop over an object or list

// YOU CANNOT DO THIS
var list = [1,2,3];
list.each(function(){

});
André Snede
  • 9,899
  • 7
  • 43
  • 67
1

From the docs:

The $.each() function is not the same as .each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array.

Felix
  • 37,892
  • 8
  • 43
  • 55
1

.each is an iterator that is used to iterate over only jQuery objects collection while jQuery.each ($.each) is a general function for iterating over javascript objects and arrays.

Shahid Karimi
  • 4,096
  • 17
  • 62
  • 104