What is the difference between $(this) and this in jQuery?

In this blog, We are going to learn, What is the difference between $(this) and this in jQuery?

this keyword:

this keyword is used to refer to the object it belongs to. The value that this stores is the current execution context of the JavaScript program.We can call all DOM methods on it but not jQuery methods.

You can check it :


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $('p').mouseover(function(){
       alert($(this).text());
  });
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

$(this) keyboard:

  • It also refers to DOM elements.
  • this is put in $(), it becomes a jQuery object.
  • We can call all jQuery methods and functions on it but not DOM methods.
  • By using $(this), you enabled jQuery functionality for the object.

You can check it :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('p').mouseover(function(){
       alert(this.innerText);
  });
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

I hope that you found this Blog helpful. If you’ve any queries, please leave comments in the comment section.

Thanks for following and reading this blog.