0

This might be straightforward, but i want to change the src of the img tag which is inside an li tag. There are 4 li tags and only the li tag which has class active should change it's img tag's src.

<ul>
   <li><img src="example.jpeg" /></li>
   <li class="active"><img src="Notexample.jpeg" /></li>
   <li><img src="example.jpeg" /></li>
   <li><img src="example.jpeg" /></li>
</ul>

Moreover, the active class toggles between the li tags to change the source...

Hunain
  • 99
  • 2
  • 8
  • 19

3 Answers3

1

Try this...

$("li.active img").attr("src", "notexample.jpg");

If you change which li has the active class then you'll need to run that code again.

If you want to change the src back when it loses the active class, do this...

$("li:not(:has(.active))".attr("src", "example.jpg");
Reinstate Monica Cellio
  • 24,939
  • 6
  • 47
  • 65
  • This might sound a little late, but i forgot to tell you guys that the li tags are dynamically added only the first li is available and active and the rest of the three are added later, so you see this only performs operation once but not for all the tags.... – Hunain Feb 08 '13 at 11:25
  • You have to do the above *when* you add the elements dynamically, not just once. – Reinstate Monica Cellio Feb 08 '13 at 11:26
  • They are changing but upon click, the src should change with the change in active class, as it toggles between the li tags – Hunain Feb 08 '13 at 12:50
  • There is no event handler for detecting class changes on elements. You would need to trigger the above code in the same code that updates the classes. – Reinstate Monica Cellio Feb 08 '13 at 13:41
1

You do it with attr() using the descendant selector of jquery.

$('li.active img').attr('src', 'newval')
Adil
  • 139,325
  • 23
  • 196
  • 197
  • This might sound a little late, but i forgot to tell you guys that the li tags are dynamically added only the first li is available and active and the rest of the three are added later, so you see this only performs operation once but not for all the tags... – Hunain Feb 08 '13 at 11:25
  • Can you tell where you want to change the src of img? – Adil Feb 08 '13 at 11:27
1
...
...
//code where you are changing the class
...
...

$('li').each(function() {
    if($(this).attr('class').indexOf("active") !== -1)
    {
        //Active class is applied
        $(this).children().children().attr("src", "assets/img/button_home_selected3.png");
    }
    else
    {
        $(this).children().children().attr("src", "assets/img/button_home_plain.png");
    }
});

...
...
asifsid88
  • 4,341
  • 18
  • 29