0

I'm at a loss at why this particulur function won't work, I've tried different things, asked friends, googled but I'm just not sure why it simply wont work.

I have a function that creates a random color, and a function that changes the backgroundcolor to that randomly generated color on a button press.

this works fine:

        function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
          document.body.style.backgroundColor = randomColors();
        }
        randomize();

it still works fine when I use

document.getElementById("change").style.backgroundColor = randomColors();

However I want to change the backgroundcolor of the body, and 2 buttons at once so I'm using

            function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
          document.getElementsByClassName("changecolor").style.backgroundColor = randomColors();
        }
        randomize();

And the colors of the body and buttons simply won't change. the elements do have the class changecolor.

      function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
          document.getElementsByClassName("changecolor").style.backgroundColor = randomColors();
        }
        randomize();
 <a class="twittershare" href="https://twitter.com/intent/tweet?text=Hello%20world" target="_blank"><button class="btn btn-primary changecolor"><i class="fa fa-twitter-square"></i></button></a>

EDIT, thanks to the comments guiding me towards the fix. Following code made it work for me:

    function randomColors() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
        function randomize() {
      let rcolor = document.getElementsByClassName("changecolor");
      let randomc = randomColors();

              for(let i = 0; i < rcolor.length; i++) {
                  rcolor[i].style.backgroundColor = randomc;
              }
        }
        randomize();
Xivik
  • 1
  • 1
  • 2
    The clue is in the name. Elements. Plural. – Quentin May 02 '18 at 20:52
  • note the plural form of "Elements" in the `document.getElementsByClassName`. You are getting an array-like structure not a single element and as such you need to loop over the collection. – scrappedcola May 02 '18 at 20:53

0 Answers0