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
brandonlind2
7,823 Pointswhat is the benefit of for .each()
I'm sure this is a novice question, but I don't understand what benefit .each() has over a normal $() selector. The $() selects all instances of what the selector is and applies what ever is applied to the selector to all its matching instances. My immediate reaction is: well .each() allows for more complex things, but you can method chain with jquery, so I can do more complex things with the normal selector also. For example, if I have 5 p elements and I write:
$("p").css("color","blue");//this would be applied to all five p elements
$("p").each(function(){$(this).css("color","blue")});//this does the
//same thing
I'm sure there is a use for .each(), I'm just currently having trouble seeing it, the normal selector seems to loop through everything already. Could someone give me example for why I would want to use .each()?
3 Answers
Marcelo Pinto
10,198 PointsHi Brandon,
The each() method allows you to iterate over each element specified by the jQuery seletor, so you can do more complex things. For example, if you have an unordered list and you wish to get the text value of each list item, then you'll have to use each() to do that:
<ul> <li>Home</li> <li>Contact</li> <li>About</li> </ul>
$( "li" ).each( function( i ) { console.log( i + ": " + $( this ).text() ); });
The console output would be: 0: Home 1: Contact 2: About
You cannot use the simple selector $() to iterate like this. You can only select all matched elements and to something with them altogether.
Hope I could help.
Jesus Mendoza
23,289 PointsHey Brandon,
In my opinion, one of the benefits of using each is that you can loop through each element and apply different styles to each one if you prefer to. With css, you apply the same style to all elements.
Robert Leonardi
17,151 PointsHI brandon,
besides in css, .each is very useful in looping an ajax response,
$.each(response,function(index,value){
});