ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

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

Updated on May 3, 2012

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.







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.

 <li class='foo'>
 <li class='foo'>
 <li class='foo'>

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.

$(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.

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.



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?

See results


    0 of 8192 characters used
    Post Comment

    No comments yet.