In this tutorial we will be looking at jQuery’s this selector. What’s a this you ask? Lets look at an example:
What we have there is an unordered list with 4 list items all with the class “option”. Now lets pretend that we want to apply a jQuery click event to one of the list items that will cause it to change to “dog”. We can do this by using:
$('.option).html("Dog");
});
But… this isn’t going to work. Why? Because how does jQuery know which elemtn with the class “option” is the one you clicked on? It doesn’t! It will replace all the elements with the class “option” to “dog”. This is where to magic of jQuery’s $(this) selector comes into play. We simply replace the selector in the click event with $(this) like, um, this…
$(this).html("Dog");
});
Volia! It works now. If you are confused think about it this way. Before we were telling jQuery:
- When a click happens on the element with a class “option”, run the event
- Get the element(s) with the class “option” and replace between the tags with “Dog”
By using this we are saying:
- When a click happens on the element with a class “option”, run the event
- Get thiselement and replace between the tags with “Dog”
Thanks for reading. No demo for this one, because it wouldn’t be a very good demo. Peace