-2

Can't quite get this code to enact on all elements within my html - I know [0] means just one - but the code doesn't work without it as its raw js

 window.onload = function yourFunction(){
    var str = document.getElementsByClassName('icon')[0].innerHTML;
    
    var res = str.replace(/_s\.png/g, ".png")
   
    document.getElementsByClassName('icon')[0].innerHTML = res;

    setTimeout(yourFunction, 5000);
}

yourFunction();

See the JSFiddle

I want to it work for all _s instances within the 'icon' classes

Community
  • 1
  • 1
Jack Allen
  • 15
  • 4

1 Answers1

0

You should use a for loop. To iterate on every element matching your array-like object of elements returned by getElementsByClassName.

window.onload = function yourFunction(){
    var elements = document.getElementsByClassName('icon');
    if (elements){
      for (var i = 0; i<elements.length; i++){
        elements[i].innerHTML = elements[i].innerHTML.replace(/_s\.png/g, ".png");
      }
    }
    setTimeout(yourFunction, 5000);
}

yourFunction();
Juan Ferreras
  • 2,801
  • 2
  • 13
  • 16