green_tea2009
green_tea2009

Reputation: 209

jquery Dollar sign

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;

Upvotes: 3

Views: 1585

Answers (3)

brianreavis
brianreavis

Reputation: 11546

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.

Upvotes: 2

nicholaides
nicholaides

Reputation: 19489

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');

Upvotes: 11

Tamas Czinege
Tamas Czinege

Reputation: 121314

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.

Upvotes: 5

Related Questions