tags:

views:

92

answers:

3

jsFiddle

I'm trying the get the ID of a button using $(this).id, but it's coming up as undefined. What am I doing wrong? Thanks for reading.

EDIT: Code from jsFiddle example:

HTML

<button id='remove_button' type='button'>Remove</button>​

jQuery

$('#remove_button').mouseup(function(){
     alert($(this).id);
});​
+3  A: 
$(this).attr('id');

:D

EDIT

although my answer is correct, the better way to do it is like dana said. So, you should accept dana answer instead of mine.

Mario Cesar
You should really be using `this.id`, and not the above. With the above you're essentially running once around the block and then kneeling down and tying your shoelaces instead of simply kneeling down and tying your shoe laces. ------- You should reserve the use of `.attr()` for attributes that have cross browser compatibility issues, or in situations where you can't use the DOM element directly (e.g. if you are given a variable that is a jQuery object).
Peter Ajtai
I guess you're right. :)
Mario Cesar
+7  A: 

$(this)

Gives you a reference to a jQuery object. You can either use the attr() function like Mario says, or even just do this:

this.id

dana
+1 Definitely use this approach. It's silly to wrap `this` in a jQuery object and call a method to access a property that's right there in the first place.
patrick dw
+2  A: 

You can use either:

this.id // <== more efficient and faster

or

$(this).attr("id")

this is a DOM element, as you can see on this MDC reference page you can use the id property of a DOM element to set or get that element's id.

You can create a jQuery object out of this by wrapping it like so: $(this). $(this) is not a DOM element, so it doesn't have the id property. Instead, you can use the .attr() jQuery method to get the id of the DOM element that is being represented by the jQuery object $(this).

Whenever you can use native DOM properties directly, it is faster than using jQuery methods, so this.id is more efficient than $(this).attr("id").

jsFiddle example

Peter Ajtai