Lesson 5. Why use $(this) and not $('.post')?


#1

My code for lesson 5 was just about right and is now working fine, however I still don't understand how $(this) works as a selector (on line 10) and why $(this) is used and not $('post') to refer to the content of the status-box.

I don't understand how the code recognizes that $(this) refers to 'post' (line 3) and what class of thing $(this) is. Would it also be correct to use $('post') in the place of $(this) and why/ why not? Any help would be much appreciated.

Here's the lesson:

https://www.codecademy.com/courses/web-beginner-en-hk5qh/0/5?content_from=make-an-interactive-website%3Ajquery-dom-manipulation#


#2

Hey Freesian,

this refers to the current object (I think). These links can explain it way better than me :smile::

Yes. I think that the reason for using $(this) instead of $('.post') is because it makes it more clear that we're working with the current thing (.post), rather than some totally different element.


#3

this is also good for referencing the current element, if it could be one of several. For example, if you have a web page where you want to change the color of a box when it's clicked and you have lots of boxes, you could use one jQuery function to set up what happens on clicking, use a class (ie. 'boxClass') to apply the event handler, and inside the function you could use this to refer to the actual box that was clicked, without needing to know it's ID or anything else about which one it was.