Dušan
Dušan

Reputation: 498

jquery $(this) returns [object object] instead of DOM reference

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

Answers (5)

user2844991
user2844991

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

Andreas Louv
Andreas Louv

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

uncle lee
uncle lee

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

p e p
p e p

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

Mika Tuupola
Mika Tuupola

Reputation: 20377

To get the DOM element use $.get():

 $(this).get(0); 

Upvotes: 3

Related Questions