Posts | Comments | Email

Using jQuery’s this selector

In this tutorial we will be looking at jQuery’s this selector. What’s a this you ask? Lets look at an example:

<ul>
    <li class="option">Cat</li>
    <li class="option">Rat</li>
    <li class="option">Hat</li>
</ul>

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').click(function(){
        $('.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…

    $('.option').click(function(){
        $(this).html("Dog");
    });

Volia! It works now. If you are confused think about it this way. Before we were telling jQuery:

  1. When a click happens on the element with a class “option”, run the event
  2. Get the element(s) with the class “option” and replace between the tags with “Dog”

By using this we are saying:

  1. When a click happens on the element with a class “option”, run the event
  2. 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

Share

Comments are closed.