jQuery $(this) keyword

jquery find
jquery each
javascript this
jquery parent
jquery on click
jquery documentation
jquery class selector
$(this) in javascript

Why is it important to use $(this) instead of re-selecting the class?

I am using a lot of animate and css editing in my code, and I know I can simplify it by using $(this).

When you perform an DOM query through jQuery like $('class-name') it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.

When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this). Like so:

$('.class-name').on('click', (evt) => {
    $(this).hide(); // does not run a DOM query
    $('.class-name').hide() // runs a DOM query
}); 

$(this) will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.

Some more information:

Web Performance with jQuery selectors

Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:

In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

The JavaScript “this” Keyword Deep Dive: jQuery Click Handlers , The native JavaScript HTML element does not have a “toggleClass” method, but jQuery does. So, by wrapping the JavaScript “this” keyword with jQuery, $(this)  When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $ (this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

$(document).ready(function(){
   $('.somediv').click(function(){
   $(this).addClass('newDiv'); // this means the div which is clicked
   });                         // so instead of using a selector again $('.somediv');
});                           // you use $(this) which much better and neater:=)

jQuery(), find() method, so $( "span", this ) is equivalent to $( this ).find( "span" ) . Using DOM elements. The second and third formulations of this function create a jQuery​  The this keyword is one of the most widely used and yet confusing keyword in JavaScript. Here, you will learn everything about this keyword. this points to a particular object. Now, which is that object is depends on how a function which includes 'this' keyword is being called.

Have a look at this code:

HTML:

<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>

JS:

$('.multiple-elements').each(
    function(index, element) {
        $(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
    }
);

this refers to the current element that the DOM engine is sort of working on, or referring to.

Another example:

<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>

Hope you understand now. The this keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)

The JavaScript this Keyword, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  JavaScript this keyword can be very confusing. This tutorial will help you understand how it works in different contexts and environments and how to use it.

using $(this) improves performance, as the class/whatever attr u are using to search, need not be searched for multiple times in the entire webpage content.

jQuery Syntax, $(this).hide() - hides the current element. $("p").hide() - hides all <p> elements. Let's understand the concept. The "this" keyword always points to the global object, if we do not specify the full namespace. In this example, we have declared two variables with the same name.

I'm going to show you an example that will help you to understand why it's important.

Such as you have some Box Widgets and you want to show some hidden content inside every single widget. You can do this easily when you have a different CSS class for the single widget but when it has the same class how can you do that? Actually, that's why we use $(this)

**Please check the code and run it :) ** enter image description here

  (function(){ 

            jQuery(".single-content-area").hover(function(){
                jQuery(this).find(".hidden-content").slideDown();
            })

            jQuery(".single-content-area").mouseleave(function(){
                jQuery(this).find(".hidden-content").slideUp();
            })
             
        })();
  .mycontent-wrapper {
      display: flex;
      width: 800px;
      margin: auto;
    }     
    .single-content-area  {
        background-color: #34495e;
        color: white;  
        text-align: center;
        padding: 20px;
        margin: 15px;
        display: block;
        width: 33%;
    }
    .hidden-content {
        display: none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mycontent-wrapper">
    <div class="single-content-area">
        <div class="content">
            Name: John Doe <br/>
            Age: 33  <br/>
            Addres: Bangladesh
        </div> <!--/.normal-content-->
        <div class="hidden-content">
            This is hidden content
        </div> <!--/.hidden-content-->
    </div><!--/.single-content-area-->

    <div class="single-content-area">
        <div class="content">
            Name: John Doe <br/>
            Age: 33  <br/>
            Addres: Bangladesh
        </div> <!--/.normal-content-->
        <div class="hidden-content">
            This is hidden content
        </div> <!--/.hidden-content-->
    </div><!--/.single-content-area-->


    <div class="single-content-area">
        <div class="content">
            Name: John Doe <br/>
            Age: 33  <br/>
            Addres: Bangladesh
        </div> <!--/.normal-content-->
        <div class="hidden-content">
            This is hidden content
        </div> <!--/.hidden-content-->
    </div><!--/.single-content-area-->

</div><!--/.mycontent-wrapper-->

jQuery's this: demystified, this (or self) is a keyword which can be used in instance methods to refer a jQuery object using the current DOM element $(this).attr('target',  this keyword refers to an object, that object which is executing the current bit of javascript code. In other words, every javascript function while executing has a reference to its current execution context, called this. Execution context means here is how the function is called.

Cool Stuff With jQuery - this vs. $(this), // anti-pattern, constructors should not cause side-effects! $( '.bar' ).click( this . `this` is a javascript keyword with a somewhat complex set of rules governing how it’s interpreted at runtime. `self` has no particular meaning in javascript and can be used as a variable name.

Avoiding the this keyword on jQuery related code | Blog, One of the most confusing aspects of jQuery is how it assigns scope And what easier way to have access to it than by using the this keyword? 'this' is a DOM element // wrap 'this' in a jQuery object var $this = $(this); // now  A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode. In most cases, the value of this is determined by how a function is called (runtime binding).

What is this?, In jQuery, the class and ID selectors are like those in CSS. a class, you can grab the specific element that triggered the element by using the this keyword. Here's the syntax: $(selector).mousedown(function); For example: Definition and Usage The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

Comments
  • You are, most likely, getting downvoted because there is a plethora of information out there if you do a Google search. Such as: remysharp.com/2007/04/12/jquerys-this-demystified
  • possible duplicate of Using the context of the 'this' keyword with jQuery
  • jQuery 1.3.2 is perhaps a little outdated even as of your answer in 2012. I would personally suggest that this 'performance' sample be taken with a grain of salt as the newer versions are more efficient in most points since 1.3.2
  • Link is dead now :(
  • Dead link, please consider revising your answer