title: Insert image src into Javascript Array by Class Name
body: <p>I'm trying to create a JavaScript that will randomize images on page refresh. I'm not really familiar with JS so I've been having a bit of trouble. </p>
  
  <p>I've succeeded in building a successful program by hard coding the image url sources into the JS array, but this is not a possibility for what I am coding this for because the user will dictate what set of images will display. The user will not have access to the JS. So the array would get the image sources from the html. What I've been trying to do is use "getElementByClassName" and insert into the array by for loop. But it doesn't seem to be working. I'm sure there is a more efficient way to do this as well, so feel free to enlighten me.</p>
  
  <p>Here is the code I have so far:</p>
  
  <pre><code>&lt;!-- Images to put into JS Array --&gt;
  &lt;img class="header" src="/image1.jpg" style="display: none;" /&gt;
  &lt;img class="header" src="/image2.jpg" style="display: none;" /&gt;
  &lt;img class="header" src="/image3.jpg" style="display: none;" /&gt;
  
  &lt;!-- Image placeholder --&gt;
  &lt;img src="/image1.jpg" id="rotate" /&gt;
  </code></pre>
  
  <p>And the JavaScript in a separate document:</p>
  
  <pre><code>// Javascript code
  window.onload = chooseHeader;
  
  var imgs = document.getElementsByClassName("header");
  var headers = new Array();
  
  for (var i = 0; i &lt; imgs.length; i++) {
      headers.push(imgs[i].src);
  }
  
  
  function chooseHeader() {
      rand = Math.floor((Math.random() * headers.length));
      document.getElementById("rotate").src = headers[rand];
  }
  </code></pre>
  
  <p>Any advice will be appreciated!</p>