JavaScript jQuery Basics Working with jQuery Collections Looping through a jQuery collection

Ewerton Luna
Ewerton Luna
Full Stack JavaScript Techdegree Student 13,167 Points

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
173,991 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!