0

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?

Community
  • 1
  • 1
stephen
  • 195
  • 9
  • 2
    `this` refers to the dom object and `$(this.id)` is not correct, it sould be `$('#' + this.id)` (id selector start with `#`) – Pranav C Balan Jul 02 '16 at 05:29

2 Answers2

1

I guess this would be more apt in your case.
console.log($(this).attr("id"));

Deepak Singh
  • 610
  • 1
  • 7
  • 23
1

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)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188