0

I have a page in a CMS that I can only edit parts of. I want to change the images it displays to larger ones. The system automatically created multiple sizes and stores them so all I would need to do is change it from /location/image-1.jpg to /location/image-2.jpg I tried the following code unsuccessfully

<body onload="replaceScript();">
<script type="text/javascript">
function replaceScript() {
var toReplace = '-1.jpg';
var replaceWith ='-2.jpg';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

Any ideas?

3
  • I tried the following code unsuccessfully please describe the problem. What happened vs what did you expect to happen, console errors, etc. Commented Jul 25, 2013 at 20:12
  • Is there a reason you want to use the function replace and not just set the address directly? For example document.body.innerHTML = '/location/image-2.jpg' Commented Jul 25, 2013 at 20:17
  • I need this to make the change across several images on the page, thats why I took that approach. I expected to see the correct images, and I still see the original ones. Commented Jul 25, 2013 at 20:33

1 Answer 1

1

My guess is you've got a series of images that you want changed and its only changing one for you. A general innerHTML replace probably isn't the best way to go about changing image sources.

Try something like this:

function replaceScript() {
    var images = document.querySelectorAll('img');
    for(var i = 0, l = images.length; i < l; i++){
        images[i].src = images[i].src.replace("-1.jpg", "-2.jpg");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.