Kuldeep Daftary
Kuldeep Daftary

Reputation: 621

How to replace src of images in list using javascript (jquery)?

I would like to replace thumbs to large in following example using js

FROM:

<ul id="slide">
<li><img src="pathtoimg/thumbs/imagename.jpg" /></li>
<li><img src="pathtoimg/thumbs/imagename2.jpg" /></li>
</ul>

To :

<ul id="slide">
<li><img src="pathtoimg/large/imagename.jpg" /></li>
<li><img src="pathtoimg/large/imagename2.jpg" /></li>
</ul>

To achieve it I used following js code

 $(window).load(function(){
 var images = $("#slide li img");
 for(var i = 0; i < images.length; i++)
{
var img = images[i];
var src = img.src.replace("thumbs","large");
img.src = src;
}
  });       

The above code works fine in modern browsers but internet Explorer 7 & 8 returns stack overflow at line : 0 error. Is there any other way to replace the src of img in list without getting above error on ie?

Thanks in advance.

Upvotes: 2

Views: 894

Answers (2)

Silviu-Marian
Silviu-Marian

Reputation: 10907

Try it like this

$(document).ready(function(){

    $("#slide > li > img").each(function(){ 
        var t = $(this);
        var src = t.attr('src');
        if(!src || typeof(src)!=='string') return;
        t.attr('src',src.replace('/thumbs/','/large/'));
    }); 

});

Upvotes: 5

bugwheels94
bugwheels94

Reputation: 31920

Try this

$(window).load(function(){
$("#slide li img").each(function(){
$(this).attr("src",$(this).attr("src").replace("thumbs","large"));
});
});

Upvotes: 1

Related Questions