user1772951
user1772951

Reputation: 19

Use javascript replace to change image url on page load

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?

Upvotes: 0

Views: 2967

Answers (1)

Shannon Poole
Shannon Poole

Reputation: 866

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");
    }
}

Upvotes: 1

Related Questions