anmml anmml - 1 month ago 12
Javascript Question

How to reload images by class name - Javascript or Jquery

How can I reload images that have a same class name ?

I tried this but it doesn't refresh the images:

<img class="refresh" src="http://www.w3schools.com/jsref/bulbon.gif"></img>
<img class="refresh" src="http://www.w3schools.com/images/colorpicker.png"></img>

// javascript: //
a=document.getElementsByClassName(refresh);
for(var c=0;c<a.length;c++)a[c].src=a[c].src;


Hope the question is clear

Answer

You can refresh your image by replacing the src with url parameter like this.

window.onload = function() {
  setTimeout(function() {
    var imgs = document.querySelectorAll('.refresh');
    if (imgs) {

      for (var i = 0, length = imgs.length; i < length; i++) {
        var pt = /\?v=.+/g;
        pt.test(imgs[i].src) ? imgs[i].src = imgs[i].src.replace(pt, "?v=" + Date.now()) : imgs[i].src = imgs[i].src + "?v=" + Date.now();
      }

    }
  }, 1000 * 60 * 5);

};
<img class="refresh" src="http://www.w3schools.com/jsref/bulbon.gif"></img>
<img class="refresh" src="http://www.w3schools.com/images/colorpicker.png"></img>