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

Michal Bednář
Michal Bednář
9,415 Points

$(this).text() vs this.text()

Hi guys,

I would like to ask you why is it important to use "$(this)" in case of using .each() mehod.

For example when I am printing the text of element to the console, I use "$(this).text()" instead of "this.text()".

Why is this working:

$("a").each(function(index){
    console.log(index, $(this).text());
  });

But this is not working anymore:

$("a").each(function(index){
    console.log(index, this.text());
  });

Thank you a lot.

1 Answer

Steven Parker
Steven Parker
229,980 Points

In these examples, "this" is a reference to a DOM element. But ".text()" is a jQuery method, and only availabe on jQuery objects.

Wrapping "this" in a call to jQuery ("$()") converts it into a jQuery object and makes the jQuery methods avaiable.

You could also get the value directly (without the jQuery method) by referring to "this.textContent".

Michal Bednář
Michal Bednář
9,415 Points

Thank you a lot Steven, I've found your answer very helpful.

I did a little bit of searching and I've found similar answer on the stackowerflow:

jQuery "wraps" around DOM elements and other objects in order to give them more functionality. Just like you pass a selector string into the jQuery constructor, you can pass a native DOM element (which this is) and it'll become a jQuery object.