jQuery $(this) keyword jQuery $(this) keyword jquery jquery

jQuery $(this) keyword


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 areference to the current DOM element. $(this) turns this into a jQueryobject and exposes jQuery’s methods. A jQuery object is nothing morethan 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:=)


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