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 trialWelby Obeng
20,340 Pointswhy create var $anchor = $(this); and not just use this.text()?
In line 10 Andrew creates
var $anchor = $(this);
and later he uses:
$option.text($anchor.text());
why not disregard line 10 and use $option.text(this.text()); ?
2 Answers
Marcus Parsons
15,719 PointsHey Welby Obeng,
We can't use this in place of $(this) because these are two separate variables. this only returns the HTML anchor element that is currently being worked on by each(), while $(this) creates a jQuery object based upon the element currently being worked on by each() that can then be called on by jQuery functions. The difference between these being that jQuery can't just add properties to an element without it first being a jQuery object; this is so that we can have functions execute on those properties of that object, such as getting the href and text portions of the anchor link, that are set by jQuery after selecting that object using jQuery.
You can see the difference between the two if you add this into your code:
$("#menu a").each(function() {
//Add two console.log statements, one for each variable in question
console.log(this);
console.log($(this));
//your code follows
Samvel Tadevosyan
7,117 PointsYou are right you can disregard line 10, but as Marcus mentioned use $(this) instead of this
you'd have:
$option.text($(this).text());
where as u can see quite many paranthesis, that is why Andrew assigned a variable to have more readable code and at the same time to remind us that $(this) object is an anchor element for the function.