Reputation: 187529
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
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
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