Alert shows [object Object]?

I'm trying to alert an id but it shows [object Object]. How to get an ID?

$('.x3').click(function() {
  var id = $(this.id);
  alert(id);
});

Upvotes: 1

Views: 4253

Answers (2)

michaelitoh
michaelitoh

Reputation: 2340

$(this) is an DOM element. Try to access the attr property of the element.

$('.x3').click(function(){
     var id = $(this).attr("id");
     alert(id);
);

Upvotes: 2

31piy
31piy

Reputation: 23859

var id = $(this.id);

This statement simply returns a jQuery wrapper object (with length 0 if there is no matching element exists on DOM).

Stringifying it to show it on alert will print [object Object]. You rather meant to use

var id = this.id; // or var id = $(this).attr('id')

Upvotes: 1

Related Questions