Dónal
Dónal

Reputation: 187529

jQuery-bound event handlers

I want to attach a 'click' event handler to the first child of an element with ID 'foo' using jQuery. I understand that the syntax for doing this is:

$('#foo:first-child').bind('click', function(event) {
    // I want to access the first child here
})

Within the handler body I want to access the element which caused the event to be fired. I've read somewhere that you can't simply refer to it via 'this', so how can I access it?

Upvotes: 0

Views: 2550

Answers (3)

Greg
Greg

Reputation: 321638

Just use "this":

$('#foo:first-child').bind('click', function(event) {
  alert(this === $('#foo:first-child')); // True
  this.style.color = "red"; // First child now has red text.
})

Upvotes: 0

Svante Svenson
Svante Svenson

Reputation: 12488

Forget what you read somewhere and go ahead and use the this keyword:

$("#foo:first-child").click(function(event) {
  $(this).css("background", "pink");
});

Upvotes: 2

Owen
Owen

Reputation: 84503

$(this).doStuff()

Upvotes: 2

Related Questions