Home »
jQuery »
jQuery Examples
What's the difference between '$(this)' and 'this' in jQuery?
Learn about the difference between '$(this)' and 'this' in jQuery/JavaScript respectively.
Submitted by Pratishtha Saxena, on December 18, 2022
$(this)
When we talk about $(this), then it is used to represent the latest element that has been targeted or pointed to. Say, we work with a <div id = 'one'> then, $(this).val() will return the value of that particular div considered. Hence, it is useful as we do not have to mention the considered element again and again.
Syntax:
$(this);
But you may have noticed the dollar sign ($) before it. Now, whenever there is a dollar sign ($) in front then it is a part of jQuery. Hence, when we represent $(this) for an element, this must be considered a jQuery statement.
this
Now, when we talk about this (without the $ sign), then also it has the same meaning, i.e., it represents the element that is currently in consideration. We need not provide the element address again and again while using this. Hence, it makes the task easier.
But the difference is that this is considered in JavaScript, whereas the previously denoted jQuery. Other than this fact, the working is same overall.
The example given below shows the usage of both $(this) & this together. When the <h3> element is clicked upon, then using $(this), the elements change the CSS color property. While, when the user clicks the <p> tag, then the color styling is changed using this.
jQuery code to demonstrate the difference between '$(this)' and 'this'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Document</title>
<style>
button{
margin-left: 1%;
margin-right: 1%;
}
h3,p{
color: darkblue;
}
</style>
</head>
<body>
<h2>Difference Between '$(this)' and 'this' in jQuery?</h2>
<h4>Click the following elements to see the resutls.</h4>
<hr>
<h3>Welcome to Include Help !!!</h3>
<p>This is a jQuery Tutorial.</p>
<h3>Thank You for Visiting !!!</h3>
<hr>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('h3').click(function(){
if($(this).css('color','crimson')); // using '$(this)';
});
$('p').click(function(){
this.style.color = 'green'; // using 'this';
});
})
</script>
</html>
Output: