One of the first few things I learned in jQuery, importantly enough that I can’t live without this function. I like to note that when I first learned jQuery, I was a bit confused of the Selectors and the each() core function. After I got a hang of how to use the Selectors, I slowly grasp the usage of each(). A few things to note about the two:
- $(selectors) selects everything that you feed to it
- The each() function is used conjunctionally with $(selectors)
- The each() function separates each of the returned item from the $(selectors) individually
Why you probably can’t live without each()
Let’s say you want to change all the paragraphs (<p>) into I don’t know… say “No paragraph for you!” to all of them:
From:
This is a paragraph 1 Second paragraph 3rd paragraph
To:
No paragraph for you! No paragraph for you! No paragraph for you!
All you have to do is one fell swoop with jQuery:
$("p").text("No paragraph for you!");
What if you want to change the text individually ONLY when the user clicks on each of the paragraph? That’s when each() comes in as hero of the day:
$("p").each(function(){
$(this).click(function(){
$(this).text("No paragraph for you!!!");
});
});
The above example / Image Swap Example using each()
That’s just the most basic use of the each() function, if you still don’t see the light with the above examples, let me know.