Search code examples
jqueryimageconditional-statementssrc

Change Image SRC on condition


Hey guys, I'm trying to display an image depending on a variable that's in my HTML. Let me explain further...

I have this HTML

<div class="container">
<span class="var">1</span>
<img class="varimg" src="" alt="" />
</div>

And I want jQuery to analyse the span.var text, then if it is:

1: return "images/1.jpg"

2: return "images/2.jpg"

3: return "images/3.jpg"

(there will be only 3...)

and then inject it in the img src...

Is it possible ? I've been trying but I'm still a newbie in jQuery...

Thanks a lot in advance !


Solution

  • $('.varimg').each(function() {
       $(this).attr('src','images/'+$(this).prev().text()+'.jpg');
    });
    

    put this code in your $(document).ready()

    2nd edit: fixed it! click here for a jsfiddle demo :)