简体   繁体   中英

Replace all img src on page load - Javascript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM