The jQuery for each loop can be very powerful. It is used just like any other jQuery function such as .click(), .hover(), etc. and it accepts a callback. As you know, or have probably guessed, the jQuery for each function loops over selected items and does whatever you’d like to targetted items.
You may be asking yourself:
But isn’t that what CSS or jQuery selectors do anyway? What’s the difference?
Standard jQuery for .each()
Not only does the jQuery for each function loop over each selected element, it also keeps track of the element index within the loop. For example:
As you can see in the example, it’s some very basic HTML with some very basic CSS. The jQuery is also relatively simple, I’m pretty sure you would be able to guess what is going on even if I didn’t explain, but I will!
The above example is selecting all
<li> elements and looping over them. It is then adding a class of ‘item-’ with its index value appended to it. The index begins at 0.
$(this) keyword references each iterated element. This is where .each() becomes very useful.
I feel that’s a pretty straight forward jQuery for each loop that you should be able to get the hang of pretty quickly if you’re fairly familiar with jQuery.
While you won’t notice the difference on small scripts and pages, it could make a difference while looping through many items and even other loops. It’s also never a bad thing to learn some javascsript when you can.
Personally I prefer doing this. It certainly isn’t much more complicated than the jQuery version.
Alright, how is $.each() any different?
Back to the point: how would we use $.each()? Without further ado, here’s an example!
In this example I’ve used an object instead of an array, but they both work pretty much the same way. First the object
obj is declared with a couple of random
value values. It is then looped over using the jQuery function. As an example, I’ve appended the values to a div and also used the key as the class of each paragraph.