Name Mon Lu

Love jQuery/CSS

Blog about Webdev

Twitter supawaza

RSS Twitter Flickr

What I am up to:


Posts Tagged ‘$(selectors)’

One of the first few things I learned in jQuery, impor­tantly enough that I can’t live with­out this func­tion.  I like to note that when I first learned jQuery, I was a bit con­fused of the Selec­tors and the each() core func­tion. After I got a hang of how to use the Selec­tors, I slowly grasp the usage of each(). A few things to note about the two:

  • $(selec­tors) selects every­thing that you feed to it
  • The each() func­tion is used con­junc­tion­ally with $(selectors)
  • The each() func­tion sep­a­rates each of the returned item from the $(selec­tors) individually

Why you prob­a­bly can’t live with­out each()

Let’s say you want to change all the para­graphs (<p>) into I don’t know… say “No para­graph 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 indi­vid­u­ally ONLY when the user clicks on each of the para­graph? 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 exam­ple / Image Swap Exam­ple using each()

That’s just the most basic use of the each() func­tion, if you still don’t see the light with the above exam­ples, let me know.