Difference between $(this) and ‘this’ in jQuery

Before writing this post, I was also confused about '$(this)' and 'this' in jQuery. I did some R&D and found out the difference between both of them. Let's first see how do we use them.

$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert($(this).text());
  });
});
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert(this.innerText);
  });
});

Got any idea about the difference?

this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.

In the second example, I have to use innerText() to show the text of the span element as this keyword is not a jQuery object yet. So I have to use the native JavaScript to get the value of span element. But once it is wrapped in $() then jQuery method text() is used to get the text of Span.

So the summary is $(this) is a jQuery object and you can use the power and beauty of jQuery, but with 'this' keyword, one need to use native JavaScript.

Feel free to contact me for any help related to jQuery. I will gladly help you.



Responsive Menu
Add more content here...