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

gaby ibarlucea
gaby ibarlucea
4,213 Points

What is the purpose of var $anchor = $(this); ? and what exactly is the keyword 'this'?

Thank you for your help in advance!

3 Answers

Aleksandr Antonov
Aleksandr Antonov
15,876 Points

it depends on the context (No code to reference) in most cases $(this) references the instance of a target being selected.

Say I have an unordered list with few list items

<ul>
    <li></li>
    <li></li>
     <li></li>
</ul>

Then if I Iterate over them

    $('ul li').each(function(){
           let item = $(this);
    });

In this scenario $(this) references the specific li that is curently being iterated over.

Hope this some what helps

So, is the code used in the example above valid for a "for loop"?

Like so:

          var $listItems = $('ul li');
          for (var i = 0; i < $listItems.length; i += 1) {
                var item = listItems[i];
               // and so on.....
          }

Steven Parker , as many times before - looking forward to your expertise!

Steven Parker
Steven Parker
231,275 Points

:bell: I got notified by your tag. But I'm not sure what you're asking here. Aleksandr's example isn't a "for loop", but a jQuery function that iterates through an array (sort of a "loop substitute"). He seems to be using it as an example of appyling "$(this)".

But your exampe is a for loop, but it doesn't illustrate using "$(this)", which seems to be the topic Gaby's original question.

Steven Parker , I'm simply asking can I use a "for loop" instead of ".each()" method on $('ul li').

Steven Parker
Steven Parker
231,275 Points

For general practice, you certainly can. But when you get to the code challenge, it will want you to specifically create a solution using the jQuery "each" function.