61

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).

logi-kal
  • 7,107
  • 6
  • 31
  • 43
agassi0430
  • 1,155
  • 1
  • 13
  • 31
  • 8
    You are, most likely, getting downvoted because there is a plethora of information out there if you do a Google search. Such as: http://remysharp.com/2007/04/12/jquerys-this-demystified/ – JasCav Sep 18 '12 at 16:48
  • possible duplicate of [Using the context of the 'this' keyword with jQuery](http://stackoverflow.com/questions/552110/using-the-context-of-the-this-keyword-with-jquery) – JasCav Sep 18 '12 at 16:56
  • +1 for @JasCav comment not because I think the original question deserves a downvote but because http://remysharp.com/2007/04/12/jquerys-this-demystified is really, REALLY helpful! – Bob.at.Indigo.Health Feb 27 '22 at 02:57

6 Answers6

91

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', function(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.

Phil
  • 10,948
  • 17
  • 69
  • 101
  • 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 – Itanex Sep 09 '13 at 16:38
  • Link is dead now :( – jarrodwhitley Mar 13 '19 at 15:40
  • Dead link, please consider revising your answer – Scott Baker Mar 20 '19 at 14:39
  • In most of the cases, the usage of `$(this)` has nothing to do with performances. – logi-kal Jan 21 '21 at 15:12
  • 2
    I don't think using an ES6 arow function in this example would actually work though. jQuery needs to apply `this` when calling the function argument which is not possible with an arrow function. – RobM Jul 28 '21 at 17:54
16
$(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:=)
Dejo Dekic
  • 2,088
  • 4
  • 27
  • 50
11

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 :)

Angad
  • 2,803
  • 3
  • 32
  • 45
4

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

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
2

$(this) returns a cached version of the element, hence improving performance since jQuery doesn't have to do a complete lookup in the DOM of the element again.

Operator
  • 504
  • 8
  • 17
2

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-->
Numan
  • 21
  • 3