Col.Cook Col.Cook - 1 year ago 105
CSS Question

JavaScript to change background color of class

I feel like I am banging my head against a brick wall here and cant figure out what I have done wrong, I have written some JS to pick a random color from an array and then I want to change the color of class to that color:

I have tried changing the class to just

aswell but still nothing, I have also added in alerts and everything seems to be passed through ok until the last line of
when nothing happens.

Also, I would prefer if I could use something like
instead of typing it into the HTML, is that possible?

var colorArray = ["#aa3333", "#33aa33", "#3333aa", "#aaaa33", "#33aaaa", "#aa33aa", "#aa6633", "#66aa33", "#33aa66"];

function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;

function chooseRandomColor() {
var randomInt = getRandomInt(0,colorArray.length);
return colorArray[randomInt];

function changeElementColor(elementString) {
var obj = document.getElementsByClassName(elementString);
var color = chooseRandomColor();
alert(color) = color;

[class^="button"] {
background-color: #333333;
float: left;
margin: 5px;
color: #aaaaaa;
text-align: center;
display: table;

[class^="button"] span {
display: table-cell;
vertical-align: middle;
text-align: center;

.button1 {
background-color: #3333ff;

.sm-sq-butt {
font-size: 10px;
height: 60px;
width: 60px;

.md-sq-butt {
font-size: 20px;
height: 120px;
width: 120px;

<a href="#"><div onclick="changeElementColor('button1')" class="button1 md-sq-butt"><span>HOME</span></div></a>

Thanks for the help!

Answer Source

getElementsByClassName() returns an collection of elements, not 1 element so will not be available.

So you need to access each element in the collection and change the style(using a loop).

for (var i = 0; i < obj.length; i++) {
    obj[i].style.backgroundColor = color;

Demo: Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download