Search code examples
javascriptselectors-api

Use querySelectorAll to add a prefix to image source


I am trying to use the weserv.nl image proxy service to load the images using their cloud servers, and don't loat the original img src image. It is to late to rewrite the src for all images and I also don't want to use jQuery for this, as my intention is to make the site faster, not slower to load. So what I want is for the img src not to load the original image, instead add a prefix to the src and load the result. Fiddle example is here. The hard part is that the images don't have id or a class assigned.

var items = document.querySelectorAll("div.separator img");
for (var i = items.length; i--;) {
    var img = items[i];
    img.src = img.src.replace(/.*?:\/\//g, "");
    img.src='https://images.weserv.nl?url='+img.src+'&w=120';
}

Solution

  • As the images doesn't have classes or Ids attached, still you can refer the parent tag and get all the images which you want to replace.

    Also in your code, you are setting the src attribute twice. Which is not required. When you're replacing the // just store it to a variable later set it to img.src

    As per your fiddle, you've two divs, so i'm using div img as selector to change the src

    var items = document.querySelectorAll("div img");
    for (var i = items.length; i--;) {
        var img = items[i],
            src = img.src.replace(/.*?:\/\//g, "");
        img.src='https://images.weserv.nl?url='+src+'&w=120';
    }
    

    DEMO