In jQuery we can do like…
$('.button').click( function() {
$(this).hide();
} );
But we can do like this too, of course:
$('.button').click( function() {
$('.button').hide();
} );
What’re advantages of using this? Isn’t that slower?
I think the answer for this question will be something like…
There are situations when only way is to use this.
Show me example of that situation then! 🙂
Which should I use primary (if both would work)?
You should use
thisif all you want to do is accessing DOM properties (that are implemented by all browsers, there are some).For example:
this.href(<a>),this.src(<img>),this.id(all elements (if set)), etc.This is the fastet way as you don’t make a function call to jQuery.
You should use
$(this)if you want to apply jQuery functions to the DOM element.You should avoid using
$(selector)if you already have a reference to that element. Searching the DOM again is way slower.You can see in line 92 of the source code that there is not much happening when you pass an HTML element.
Also note that
$(this).hide()and$('.button').hide();are not equivalent. The first will only hide the clicked element, while the second will hide all.buttonelements.