Closed
Description
It's touched upon in different areas, but I think we should have one comprehensive page that explains some useful, common issues with iterating over jQuery collections.
- The fact that there is
each
on the jQuery prototype. I see newcomers do the following too often:
$.each( $(".something"), function() {});
- On the other hand, don't
each
when it isn't necessary - most jQuery methods iterate over the entire collection
// this isn't necessary
$(".foo").each(function() {
$(this).addClass("bar");
});
// when this does the same thing
$(".foo").addClass("bar");
- The fact that you have to use
each
when you're trying to set something on individual elements based on an existing value: A lot of newcomers try to do something like the following
$(".foo").val( $(this).val() + "%" );
and are confused when it doesn't work. Explain that this
is still the window, and instead each
is necessary to operate on each element! (Explain the index and element arguments)
$(".foo").eachfunction(index, el) {
var $this = $(this);
$this.val( $this.val() + "%" );
});
- Explain the function setters with "implicit iteration" as an alternative to the above, explain how the current value is passed as the second argument instead of the element itself
$(".foo").val(function(index, val) {
return val + "%";
});