Difference Between jQuery().each() and jQuery.each()
jQuery has 2 different methods jQuery().each() (Also written as "$.each()") and jQuery.each(). Both the methods are similar in nature used for iteration or looping but the differ only at the level where they are used.
jQuery.each(): is used to iterate, exclusively, over a jQuery object. When called it iterates over the DOM elements that are part of the jQuery object.
$.each(): function can be used to iterate over any collection, whether it is an object or an array.
Related Post:
- Latest jQuery interview questions and answers
- Difference between eq() and get()
- Difference between jQuery parent() and parents()
First, let see how jQuery.each() works. To work with this function, you always need to pass a selector on which iteration needs to be performed. Consider the following HTML,
<ul> <li>foo</li> <li>bar</li> </ul>
Now below jQuery code, will select all "li" elements and loop through each of the item and logs its index and text.
$( "li" ).each(function( index ) { console.log( index + ": " + $(this).text() ); });
On the other side, $.each() is used to iterate through an object or array collection. See below jQuery code.
var obj = { one:1, two:2, three:3, four:4, five:5 }; $.each( obj, function( key, value ) { alert( key + ": " + value ); });
Got the idea about the difference. But you can also make $.each() function to make it similar to jQuery.each(). All you need to do is to instead of object or array, you can pass DOM collection to achieve the same result. See below jQuery code.
$.each($( "li" ), function( index, value ) { console.log( index + ": " + $(this).text() ); });
Feel free to contact me for any help related to jQuery, I will gladly help you.