Given:
var element = $('#element');
I'm wondering which is faster:
element.click(function(){
element.dosomething()
)}
Or:
element.click(function(){
$(this).dosomething()
)}
Or does it matter?
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
It has no special meaning. jQuery sets the global $ variable to an object with a number of special behaviors, so variables beginning with $ are often reserved for variables or values related to jQuery. This is not enforced at any level, though. You're free to use $ in variable names wherever and however you like.
Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $. get() .
Use element
.
If element
was a jQuery collection matching a single element, for example, $(
someId)
, then just use it.
If the selector was meant to match more than one element, then element
is actually elements
, a collection of elements, so, in that case you use $(this)
inside your click handler to catch the one actually clicked.
The difference is explained int he following examples:
1- Handler on single element
var table = $("#myTable");
table.click(function() {
// Same as $(this), except $(this) creates another
// wrapper on the same object (which isn't too expensive anyway)
table.doSomething();
});
2- Handler on multiple elements
var rows = $("#myTable > tbody > tr");
rows.click(function() {
// Here we have to use $(this) to affect ONLY the clicked row
$(this).doSomething();
});
3- Handler on single element, but called for multiple child elements
var table = $("#myTable");
// "on" and "live" call handler for only child elements matching selector
// (Even child elements that didn't exist when we added the handler,
as long as parent -table in this case- exists)
table.on("click", "tbody > tr", function() {
// Here we have to use $(this) to affect ONLY the clicked row
$(this).doSomething();
});
I find it assuring (and less work, a very tiny difference though) to just the existing wrapper, showing that I'm expecting a single element in this case and I'm just working with it. And use $(this)
when I'm dealing with elements of a collection of matching elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With