What does $this in jQuery mean? jQuery for beginners.

Source

What is jQuery?

If you are reading this article you may already have some jQuery experience. But for those who don't here is a simple explanation.

jQuery is referred to as a "JavaScript Library" which basically means it can be used by JavaScript to perform tasks by referencing code which has already been written. It allows JavaScript users to "write less, and do more".

In this article I will try to demystify what $(this) means in jQuery.

In the past you may have seen jQuery code similar to the following:

$(this) Example.

<script>
$(function(){

 $(.foo).each(function(){

  $(this).attr('class','bar');  

 }); 

});
</script>

Explanation.

To the trained eye, this example will be simple to understand but for those who aren't familiar with $(this) it may be a little confusing.

Consider the HTML code below.

<ul>
 <li class='foo'>
 </li>
 <li class='foo'>
 </li>
 <li class='foo'>
 </li>
</ul>

As you can see, we have three <li> elements all with a class of .foo. However, by adding our jQuery script to the page, these would all become elements with the class of .bar.

Refer the now commented code below.

<script>
$(function(){ // window.onload equivalent.

 $(.foo).each(function(){ // For each class of '.foo'

  $(this).attr('class','bar');  // Change 'this' to 'bar'

 }); // end each statement.

}); // close window.onload equivalent.
</script>

Notice that $(this) is actually refering to the class of .foo as it is contained within the .foo each function.

Please see another simple example of this below.

$(.fadeoutdiv).click(function(){

 $(this).fadeOut();
	
});

The code above would fade out any element which is clicked and has the class of .fadeoutdiv. As $(this) is contained within the .fadeoutdiv click function.

To summarise, $(this) can be used to refer to an element, class or an id of which it's function is manipulating. These are very simple examples, but practially $(this) can become a very powerful addition to your jQuery knowledge.

I hope this helps someone. Please let me know if you found this useful by voting in the poll below.

Did you find this helpful?

  • Yes
  • No
See results without voting

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working