tags:

views:

31

answers:

3

Onclick on image I need to change the background of li using jquery

LI is not immediate parent so I am not able to use parent() function in jquery

<li class="ui-widget-content ui-corner-tr ui-draggable">  
    <fb:profile-pic height="32" width="32" linked="false" uid="557103888" style="width: 32px; height: 32px;" class=" fb_profile_pic_rendered">  
        <img class="" style="width: 32px; height: 32px;" title="some name" alt="some name" src="files/t557103228_5135.jpg">  
    </fb:profile-pic> 
</li>
A: 

It's the grandparent, so .parent().parent() then.

Or use .closest('li').

KennyTM
+3  A: 

Use .closest('li').

This will give you the first ancestor of the <img> that is an <li> element.

You could also use .parents('li:first'). It uses the :first selector to ensure you only get the first result.

patrick dw
.parents('li:first') is not working but .closest('li') its working fine.I used as below$item.closest('li').css('background-color', 'red');Thank you Patrick.
Elankeeran
@Elankeeran - You're welcome. :o) Very strange that `.parents()` didn't work. Anyway, glad that `.closest()` panned out for you.
patrick dw
@patrick dw How to toggle the background color?
Elankeeran
@Elankeeran - The background color of the `<li>`? If you just want to change the color, you would do: `.closest('li').css('background','purple');` If you thought you were going to toggle it back and forth, I'd probably use a class, and then do `.closest('li').toggleClass("myBackgroundClass")`. This way it will add and remove the class with each click. (Remember to add the class definition to your style sheet.)
patrick dw
@patrick dw Thank you! but I have many li with inside image onclick on image li will get background color. suppose I clickon other li image that should get background and other should be default color its like switch selection (radio button).
Elankeeran
+1  A: 

You can do like this:

$('img[title="some name"]').click(function(){
  $(this).closest('li.ui-widget-content').css('background', 'green');
});

Since the image does not have any class or id attribute set, the title attribute is used instead. In this case any image whose title is set to some title for example gets clicked, the background of parent li with class ui-widget-content is changed using css method which is actually found with closest function which finds elements back up until specified element is found.

Sarfraz
Thanks Sarfraz... Patrick given above.
Elankeeran
How to toggle the background color?
Elankeeran