Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) AJAX and APIs Adding jQuery

Philip Kroupoderov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Philip Kroupoderov
Front End Web Development Techdegree Graduate 21,641 Points

If he wrote $("button").removeClass("selected"); then why does the each() method even exist?

I thought he would write the following and use each():

$(document).ready(function () {
    $('button').click(function () {
            $("button").each(function() {
                $(this).removeClass("selected")
              });
            $(this).addClass("selected");
      });
});

So can someone tell in which case should I use the each method and in which cases I can just call a method on a jQuery object which contains multiple elements?? And why does the each method exist in the first place when typing $("button").removeClass("selected"); will loop through all elements with the class of selected and remove the class from them??

1 Answer

Steven Parker
Steven Parker
231,236 Points

Typically, if a method exists that performs the desired operation on all elements in a jQuery object, you would use that by itself and not use ".each".

You would use ".each" when you want to apply some code to every element for which there is no handy jQuery method that can do the job.