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
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
224,872 PointsIn 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ář
9,415 PointsMichal Bednář
9,415 PointsThank 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: