Reputation: 42753
In this code, we can obtain value of element id as 2 differnt way and both way return resultat
$("#my_div").on("click", function () {
alert( $(this).attr("id") );
alert( this.id );
});
But i interest, second way, is it proper in this case? I ask this, because in code we use jquery selector and for jquery selector, write clear javascript: this is justified and will it work always? or may be better use jquery $(this) for jquery selector? or not differnce?
Upvotes: 1
Views: 105
Reputation: 16861
For choosing the best method is not always clear.
In this case you want the this.id
, because the other solution requires much more calls behind the scenes (obvious calls to jQuery
and attr
).
If you need more information that mite differ from browser, you want the jQuery way.
Upvotes: 1
Reputation: 943142
The main jQuery constructor can take a number of different types of argument.
In that context, this
is not a selector, it is an HTMLElementNode (which jQuery calls an element).
This is perfectly OK and documented.
There is no need to spend the resources in wrapping an element in a jQuery object if you are just going to grab its ID. There aren't any compatibility problems between browsers for that.
Grabbing the id
property of an HTMLElementNode takes less code and is faster then wrapping the whole thing in jQuery.
Upvotes: 3
Reputation: 87073
Yes, your second way is proper.
$("#my_div").on("click", function () {
// this is available within this function
alert( this.id );
});
this
refers to an HTMLDOMElement
within the function, and wrapping that this
within $()
will give you an jQuery object.
If you define another function within the click
handler. Ex:
$("#my_div").on("click", function () {
// keep reference of this
var that = this;
function test() {
// this will not available here directly
// instead of that you can use reference
alert(that.id);
}
});
And $(this).attr('id')
, this.id
or $(this).prop('id')
will give you the same result.
Upvotes: 1
Reputation: 145368
this.id
will give you the internal DOM element property while $(this).attr("id")
returns the value of 'id' attribute.
The alternative to this.id
in jQuery is using prop()
method: $(this).prop("id")
. However, using pure this.id
construction will be easier and faster.
Upvotes: 6