Reputation: 498
In this situation
$(document).on('click', '.photo-actions .photo-link', function () {
console.log($(this));
});
$(this)
retrurns [object object]
instead of DOM refference for an element which is clicked.
Why is this the case and how to get the DOM reference?
and if i write $(this).attr('id');
it returns the id of element which it should.
Upvotes: 2
Views: 15954
Reputation:
this
IS the DOM Element. By wrapping it inside a $
function call you obtain an object that inherits from jQuery.prototype
.
Therefore, in order to get the id, you can do both: this.id
or $(this).attr("id")
.
If you would have received a jQuery object, you could have extracted the DOM element by using $myObj.get(0)
or $myObj[0]
, but it is not the case for you.
Upvotes: 0
Reputation: 47099
[object Object]
is a string representation of an Object in JavaScript.
Consider this:
alert({}); // [object Object]
alert(document.body); // Old browsers [object Object] newer browsers [object HTMLBodyElement]
If you see the string representation of an jQuery object or any other instance of a function it will be [object Object]
.
Try fiddeling around with this:
String({}); // [object Object]
// Internally .toString is called:
var myObj = {};
myObj.toString(); // [object Object]
TLDR: You have no errors!
Upvotes: 0
Reputation: 31
$(this) returns [object object] because it's a jquery object.Try console.log(this), you will get the
dom element you need.
Upvotes: 3
Reputation: 6674
Use either simply 'this' for the DOM reference, or '$(this)[0]'. The value of '$(this)' is a jQuery object that provides you with all of the jQuery functionality.
Upvotes: 0