Do these two snippets of code do identical things? If yes, when should one be used over the other? (besides when you need to do something involving i
or value
)
$("foo").each(function(i,value) {
$(this).empty();
});
vs.
$("foo").empty();
In general can it be assumed that $("foo").someMethod()
means "run somemethod()
on each element that matches the selector, except if the name of the method is each
? (ie each is a special case)
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 an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.
To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.
each() loop : Lower performance compare to other loops (for games/animations/large datasets) Less control over iterator (skip items, splice items from list, etc). Dependency on jQuery library unlike for, while etc loops!
Assuming you're referring to stock jQuery functions, yes, the two snippets of code are identical.
You should use the each()
function either when you want to work with the index, or to prevent long function chaining.
Your understanding of $('foo').someMethod()
is true of jQuery methods. But be warned, some plugins may handle the selector in a different manner, or only affect the first matched element for example.
Yes, most jQuery function are designed like this.
Look at the code example:
$.fn.someMethod = function() {
return this.each(function() {
do_something(this);
});
};
So even you could use .each
again, you should just use:
$(selector).someMethod();
not
$(selector).each(function() {
$(this).someMethod();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With