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(){});
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(){});
$('.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.
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.
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(){
});
.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.