0

I'm trying to replace all img src's on my page, when they have a certain url in them. So far I'm able to log all the replaced img src's, but my final step would be to change them on my page.

function replaceMyImgs() {

// put live url here
var liveUrl = "via.placeholder.com";

// find the local url
var localUrl = "testdomain.com";

// replace the local url for the live url
var newUrl = localUrl.replace(/testdomain.com/g, liveUrl);

// console.log(newUrl);

// get all images and push them in an empty array
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];

for (var i = 0; i < imgs.length; i++) {
  imgSrcs.push(imgs[i].src);
}

imgSrcs.forEach(function(src) {
   // log all the found img srcs
   var newSrc = src.replace(/testdomain.com/g, liveUrl);

   imgs.src = newSrc;

   console.log(imgs.src);

 });

}

window.onload = replaceMyImgs;

See my pen: https://codepen.io/kleefaan/pen/yqzBVv

S. Wannsee
  • 15
  • 6

1 Answers1

1

Instead of pushing all elements into an array you can do the replace in the for loop like this:

// get all images
var imgs = document.getElementsByTagName("img");

for (var i = 0; i < imgs.length; i++) {
  var newSrc = imgs[i].src.replace(/testdomain.com/g, liveUrl);
  imgs[i].src = newSrc;
  console.log(imgs[i].src);
}
Martin
  • 2,411
  • 11
  • 28
  • 30