stephen stephen - 5 months ago 8
jQuery Question

id of element that fired event (this) $(this) unexpected behavior

I have this bit of code:

<button id="hit">hit</button>

$('button').click(function(){
console.log(this.id);
$(this).append("ok");
});


I'm assuming that
$(this)
is necessary to refer to
$(button)
, based on Getting the ID of the element that fired an event, which also works in the following line that works as expected (adds 'ok' to the button text). I can't figure out why
console.log(this.id);
works and the following do not:

console.log( $(this.id) );


$('button').click(function(e){
console.log(e.target.id);
});


From what I can tell, this is the opposite of what's supposed to be happening:
$(this)
seems like it should be referring to the jQuery object--I don't see how the examples that work have a (this) and a $(this) that refer to the same object. Where am I getting my understanding wrong?

Answer

Inside the click event handler this refers to the dom object, to convert it to jQuery object wrap it with $ like $(this).

And $(this.id) is not correct selector, which search for the tag element hit. Since it's an id of the element it should start with #.

$('#' + this.id)