0

How can I modify/update elements with unique class name in JavaScript?

The following code is not working:

document.getElementsByClassName("test").style.backgroundColor = "blue";

HTML markup:

<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
khassepaz
  • 45
  • 1
  • 7

2 Answers2

2

getElementsByClassName returns an array-like object, so you'll have to pluck out individual elements, or iterate through the whole thing!

var elements = document.getElementsByClassName("test");
for(var i = 0; i < elements.length; i++) {
  elements[i].style.backgroundColor = "blue";
}
therobinkim
  • 2,500
  • 14
  • 20
0

See: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

getElementsByClassName() returns an HTMLCollection, so you need to specify which of the matching elements will have the style applied to it.

Demo: https://jsfiddle.net/jnu44ck0/

Chris Bier
  • 14,183
  • 17
  • 67
  • 103