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

Just when I thought I had "this" figured out...

Can someone please explain to me how "this" works in this code?

$("#menu a").each(function() {
   var $anchor = $(this);

Treehouse is under some maintenance so I couldn't open the workstation. This is for the jquery basics tutorial - creating a mobile dropdown. I'll post the code tomorrow with everything if it isn't answered already.

2 Answers

So i tried answering this twice earlier, but my answers just sort of got lost with maintenance.

this in your example refers to each anchor element within #menu that gets picked up by .each(). The variable $anchor will temporarily hold each anchor iteration, to be manipulated until it kicks to the next anchor. Each of these elements are turned into a jQuery object after being returned from .each(), allowing them to be referenced using "this." For example, let's pretend there's three anchor tags nested in a div with an id of menu. Using the code above, we'll get something like this:

  1. .each() selects the first anchor within #menu
  2. the first anchor is temporarily assigned to a variable (referenced using this)
  3. .each() selects the second anchor within #menu
  4. the second anchor replaces the first, temporarily being assigned to a variable (referenced using this)
  5. .each() selects the third anchor within #menu
  6. the third anchor replaces the second, temporarily being assigned to a variable (referenced using this)

Thanks Ricardo. The 'this' keyword kinda throws me off. It doesn't seem to work in a consistent fashion. I "knew" that is what was happening, but I didn't know why.

I will explain this code smoothly..get ready ;) $("#menu a").each(function() { var $anchor = $(this); <p>First we are selecting an element with an ID of 'menu' and accessing all its anchor elements using the jQuery method. Then for EACH anchor we are going to execute a function. In inside the function we are creating a variable called $anchor and setting its value to a jQuery method containing 'this'. </p> In this code the 'this' means the anchor we selected in the first line of code Hope this helped. Rate my answer