1

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);
});
31piy
  • 23,323
  • 6
  • 47
  • 67

2 Answers2

2

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

$('.x3').click(function(){
     var id = $(this).attr("id");
     alert(id);
);
michaelitoh
  • 2,317
  • 14
  • 26
  • 1
    What do you mean, "Dom element, not an object"? Every DOM element is an object. – Amadan Aug 24 '18 at 04:44
  • 1
    `this` is a DOM element. `$(this)[0]` is a DOM element. `$(this)` is NOT a DOM element but a jQuery object. [See more](http://api.jquery.com/Types/#jQuery) – Hikarunomemory Aug 24 '18 at 05:01
  • Thank you for the clarification @Hikarunomemory, any way the answer was updated after Amadan comment. – michaelitoh Aug 24 '18 at 12:27
1
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')
31piy
  • 23,323
  • 6
  • 47
  • 67