tags:

views:

121

answers:

3

i have this html:

<ul id="list1" class="eventlist">
  <li>plain</li>
  <li class="special">special <button>I am special</button></li>
  <li>plain</li>
</ul>

and I have this jquery code:

$('#list1 li.special button').click(function(event) {

  var $newLi = $('<li class="special"><button>I am new</button></li>');
  var $tgt = $(event.target);
});

My question is what is the difference between

var $tgt = $(event.target);

and

var $tgt = event.target;
+4  A: 

In the first case, the local varialbe $tgt will hold the jQuery element (wrapped around a DOM element), in the second case it will hold the DOM element.

You cannot use the jQuery manipulation methods (such as .val()) directly on DOM elements, hence you need to convert it to a jQuery element first if you want to do so.

DrJokepu
+5  A: 

event.target is a reference to the DOM node. $(event.target) is a jQuery object that wraps the DOM node, which lets you use jQuery's magic to query manipulate the DOM.

In other words, you can do this:

$(event.target).addClass('myClass');

but you can't do this:

event.tagert.addClass('myClass');
nicholaides
+2  A: 

I'd advise just using $(this) to grab the element. jQuery does that internally so you don't have to:

$('#list1 li.special button').click(function() {
    var $tgt = $(this);
});

To answer your question: $(event.target) will be extended with jQuery, and event.target won't.

brianreavis
To clarify, AFAIK the difference between this and event.target in a jQuery event handler is that 'this' is the DOM element you assigned the handler on. event.target is the element that actually got the event. E.g. if you put a click handler on a div containing other code, the handler will get events where this is the div tag, and event.target is whatever the most-nested tag was that actually got clicked on.
Walter Mundt
Not really... If a `click` event is bound to all paragraph tags in a document, for instance, `this` inside the handler will refer to the the single element that was clicked---not all of the paragraphs that the handler was bound to. `$('p').click(function(){ /* (this) will will reference the particular paragraph that was clicked */ });`
brianreavis