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!

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 (2014) Creating a Mobile Drop Down Menu Perform: Part 1

Welby Obeng
Welby Obeng
20,340 Points

why create var $anchor = $(this); and not just use this.text()?

In line 10 Andrew creates

var $anchor = $(this);

and later he uses:


why not disregard line 10 and use $option.text(this.text()); ?

2 Answers

Hey 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
//your code follows
Samvel Tadevosyan
Samvel Tadevosyan
7,117 Points

You are right you can disregard line 10, but as Marcus mentioned use $(this) instead of this

you'd have:


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.