1

Possible Duplicate:
What is the difference between $(this) and this

Anyone guide the difference of Jquery this and $(this). Like in the below code I when I try to use $(this).id does not work and if I use this.id its working. I thought there is no difference between $(this) and this. I appreciate If someone explain the reason.

$(function($){
 //This work

  $('p').append( $('input').map(function(){   
     return  this.id;
  }).get().join(', '));

//This is not working? Could you explain what's the reason

  $('p').append( $('input').map(function(){   
     return  $(this).id;
  }).get().join(', '));

});
Community
  • 1
  • 1
Tariq
  • 147
  • 1
  • 9

1 Answers1

2

"this" is a direct reference to the DOM node, without any interference from jQuery. It would be the same as calling document.getElementById();

Wrapping it with $() returns a jQuery object, which has a different set of properties and methods. In particular, the jQuery object does not have an id attribute - you would have to instead do

$(this).attr("id")

Both syntaxes are correct, however if you simply want to grab the id of the DOM node, "this.id" would be faster.

James Davies
  • 9,602
  • 5
  • 38
  • 42