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 jQuery Basics Working with jQuery Collections Looping through a jQuery collection

Couldn't she have done this instead?

When explaining the each method, Treasure put it this way:

$('a').each(function(index, element){
    console.log(index, $(element.attr('href'));
});

Why is she using the jQuery selector in 'element' if, in this case, the 'element' variable has already a hold on the html element?

I tried doing this instead and it works:

$('a').each(function(index, element){
    console.log(index, element.href);
});

Is there any specific reason for using the jQuery function to target the element if she already has a hold on it?

1 Answer

Steven Parker
Steven Parker
231,269 Points

Remember that the course examples are intended to help you learn jQuery, not just perform a certain task. The course method uses the opportunity to demonstrate converting an element into a jQuery object, and to employ the jQuery "attr" method.

It's quite common for there to be other, and often more efficient ways to refactor a course example. The fact that you recognize them is simply evidence of your learning progress. Good work!