-1

I'm using document.getElementsByClassName to change the background color of one of the multiple elements with the specified class name.

I have the error message in the title and I cannot find any mistakes, please spot them if there is one:

     function process() {
if (dv1 === 1 && dv2 === 1 && dv3 === 1) {
    turns = 0;
    document.getElementsByClassName('dot').style.backgroundColor = "black";
 }
}

<div class="dot" id="dot_01" onclick="dot_01()"></div>
<div class="dot" id="dot_02" onclick="dot_02()"></div>
<div class="dot" id="dot_03" onclick="dot_03()"></div>
<div class="dot" id="dot_04" onclick="dot_04()"></div>
<div class="dot" id="dot_05" onclick="dot_05()"></div>
<div class="dot" id="dot_06" onclick="dot_06()"></div>
<div class="dot" id="dot_07" onclick="dot_07()"></div>
<div class="dot" id="dot_08" onclick="dot_08()"></div>
<div class="dot" id="dot_09" onclick="dot_09()"></div>
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Benn
  • 55
  • 1
  • 1
  • 8

3 Answers3

1

Try to loop trough the elements.

var elems = document.getElementsByClassName('dot');
for(var i = 0; i < elems.length; i++) {
    elems[i].style.backgroundColor = ‘black’
}
MevlütÖzdemir
  • 3,180
  • 1
  • 23
  • 28
0

getElementsByClassName returns an HTMLCollection. You need to iterate through that and set the style of the collection elements. Currently, you are trying to set the properties on the style reference of the HTMLCollection object itself, and it does not have one.

Smilliam
  • 99
  • 1
  • 5
  • I'm not sure I understand, how does that apply to the script? What can I change? – Benn May 16 '18 at 22:36
  • See the reply by @MevlütÖzdemir for code. From the HTMLCollection docs I linked earlier, an HTMLCollection is an "array-like object." So you want to loop over the results that you get from your `document.getElementsByClassName` call. – Smilliam May 16 '18 at 22:39
  • Got it, I understand it now, can you cite any other website that discuss HTMLCollections? – Benn May 16 '18 at 22:39
  • see if this helps https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementsbyclassname – highhope May 16 '18 at 23:31
0

Try the following:

function process() {
    if (dv1 === 1 && dv2 === 1 && dv3 === 1) {
    turns = 0;
    let elems = document.getElementsByClassName('dot');

    for (let elem of elems) {
        elem.style.backgroundColor = "black"
    }
  }
}