views:

1751

answers:

4

Hi,

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?

Cheers, Don

+2  A: 
$(this).doStuff()
Owen
A: 

I'm not sure I understand the question... like you said - 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
})
Greg
+2  A: 

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

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

Just to add to RoBorg's reply, one little correction is that:

 this === $('#foo:first-child') // returns false
 $(this) === $('#foo:first-child') // returns true

this references the HTML element itself, $(this) simply turns it into a jQuery element.