1

I want to change CSS property background color using class name in JavaScript. My code is as below

function changeColor(){
    document.getElementsByClassName("flex-items").style.backgroundColor = "blue";
}

The function changeColor() is called with a onclick event of a button.

<button onclick="changeColor()">Change Color</button> 

Is there a solution to this problem?

[Note there are many div boxes with class name "flex-items" and I want to change all their background color on a single click.]

Ajinkya
  • 843
  • 10
  • 32
  • You're supposed to do some research before asking here. The short answer is that `.getElementsByClassName()` returns more than one `HTMLElement` so your code has address that. Or just use jQuery. –  Sep 05 '17 at 16:35

1 Answers1

1

Just push them to an array and loop it through.

window.changeBG = function() { 
    var items = document.getElementsByClassName('item');
    for(var i in items) items[i].style.backgroundColor = 'red'; 
}

https://jsfiddle.net/gugalondon/69syLdg1/

gugateider
  • 1,983
  • 2
  • 13
  • 17