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


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:



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.


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.