0

I am kinda new in this programming thing and I am trying to improve myself by doing some challenges. However I am stuck on sth. When the button is clicked I want to change the background color of body and some and button. I managed to change the color of body but stuck on and button. For your info I am using Bootstrap elements in my code as you can understand.

Thanks in advance for your helps

function changeColor (color){
  var choosenColor = Math.floor(Math.random() * 12) + 1;
  document.body.style.background = colors[choosenColor];
  document.body.style.color = colors[choosenColor];
  document.getElementsByTagName("a").style.background = colors[choosenColor];
}


var colors = ['#16a085', '#27ae60', '#2c3e50', '#f39c12', '#e74c3c', '#9b59b6', '#FB6964', '#342224', "#472E32", "#BDBB99", "#77B1A9", "#73A857"];
<div class="col-12 social-media">
    <a href="" id="tweet-quote" class="btn btn-primary">
        <i class="fa fa-twitter"></i>
    </a>
    <a href="" id="tumblr-quote" class="btn btn-primary">
        <i class="fa fa-tumblr"></i>
    </a>
    <button id="new-quote" class="btn btn-primary" onclick="changeColor()">New Quote</button>
</div>   

Screenshot

Icarus
  • 1,627
  • 7
  • 18
  • 32
sinan
  • 570
  • 5
  • 24
  • `document.getElementsByTagName("a").style.background` wrong. see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName – epascarello May 07 '18 at 19:12
  • `getElementsByTagName` returns an HTMLCollection, which is an array like structure. – Taplar May 07 '18 at 19:15
  • It is also stated on referred topic, I used getElementsById but still not working. – sinan May 07 '18 at 19:24
  • You will want to use a `for` loop in place of your last line: ```var buttons = document.getElementsByTagName("a"); for(var i = 0, max = buttons.length; i < max; i++) { buttons[i].style.background = colors[choosenColor] }``` – trevorp May 07 '18 at 19:26
  • this has been closed for answers but this will work for you: `function changeColor() { var choosenColor = Math.floor(Math.random() * 12) + 1; document.body.style.backgroundColor = colors[choosenColor]; document.body.style.color = colors[choosenColor]; document.getElementById("button").style.backgroundColor = colors[choosenColor]; } var colors = ['#16a085', '#27ae60', '#2c3e50', '#f39c12', '#e74c3c', '#9b59b6', '#FB6964', '#342224', "#472E32", "#BDBB99", "#77B1A9", "#73A857"];` – Claire May 07 '18 at 19:27
  • you are trying to pass a color into your function, which it does not need. also you must call your link by its ID, which i gave it `ok do it` – Claire May 07 '18 at 19:28
  • This [JSFiddle](https://jsfiddle.net/53a6e1g7/) shows how a loop would work without targeting its ID. – trevorp May 07 '18 at 19:48
  • Thank you guys I managed to solve the problem with the help of Tom – sinan May 08 '18 at 19:42

0 Answers0