jQuery: applying selector within 'this'

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>

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

    //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);

jquery selector 'this' example

When someone clicks on the list item, the image is toggled (tick/cross). The second parameter to the $() is the context. The change (changing the src attribute calling the attr() method) affects only the context (in this case, the ‘this’ parameter).

The context parameter helps limiting the scope of the change.

See the demo

Download code

Comments on this entry are closed.

  • commenst system creation in php

  • pls tell

  • Thanks! Took quite a bit of searching for me to finally find this answer which you so eloquently gave.

  • Thanks for the sample

  • Hello Everyone,

    i have some simple javascript questions to seek advice.
    In my form, i have two mutually exclusive options for user to choose:

    i) Checkbox: “If arrival time is uncertain”
    ii) Dropdownbox1: “Time arrived”: HH, Dropdownbox2: MM, Dropdownbox3: AM/PM

    What i after is… if the checkbox.checked is true, then the dropdownbox1, dropdownbox2 and dropdownbox3 will ALL be disabled. And certainly all other times the dropdown boxes are enabled and the checkbox is unchecked.

    Why are the time (HH, MM, AM/PM) separated into 3 dropdowns? I really dont know. It was a given feature from a downloaded form 😉 Do i have to pass an array or something like that?

    Hope to get some helps here.

  • I am using your validation script. It works well. I am also using another script that prints output from a form. How do I go from the validation script to the print script?

  • Thank you for this nice advice 🙂 I will use this in my contact form with multiple selection.