jQuery this selector

http://www.javascript-coder.com/jquery/jquery-selector-this.phtml

 

When you handle events for a particular element, it is often required to make a change only within children of the element. Here is how to do it.

Suppose this is the HTML code

<h2>Select the services you want:</h2>
<ul id='services'>
<li><img src='tick.gif'>Build a Website</li>
<li><img src='tick.gif'>Page design</li>
<li><img src='tick.gif'>Flash banners</li>
<li><img src='tick.gif'>SEO</li></ul>
</ul>

When someone clicks on each of the service, the image is to toggle.
Here is the jQuery code to do that

$(function()
{
    //handle the click for each of 'li'
    $('ul#services li').click(function()
    {
        //toggle the image
        var newimg =
            $('img',this).attr('src') == 'tick.png' 'cross.png' 'tick.png';
        /*
        notice the second parameter to $() is the context.
         'this' is the 'li' that was clicked.*/
        $('img'this).attr('src',newimg);
    });
});

Leave a Reply