There are such divas <html>

 <div class="colDiv">Color 1</div> <div class="colDiv">Color 2</div> <div class="colDiv">Color 3</div> 

here is js

 var colorArray = [ document.getElementsByClassName('colDiv'), document.getElementsByClassName('colDiv'), document.getElementsByClassName('colDiv') ]; 

so getting the items you need to change color 2 diva

how to do it?

Did this:

 myDiv.style.color = "blue"; 

tried this:

 for (i = 0 ; i < colorArray.length; i++) { colorArray[i].style.backgroundColor = "#AA0000"; } 

does not work.

    3 answers 3

    getElementsByClassName returns an array, so just like this:

     var colorArray = document.getElementsByClassName('colDiv'); colorArray[1].style.backgroundColor = '#AA0000'; 
     <div class="colDiv">Color 1</div> <div class="colDiv">Color 2</div> <div class="colDiv">Color 3</div> 

    • EEE works !!! 10X !!! - EugeneTM

    The getElementsByClassName method already returns an array (strictly speaking, HTMLCollection ): there is no need to add the result to the array and, moreover, put the same result into the array 3 times. It will be enough to do this:

     var colorDivs = document.getElementsByClassName("colDiv"); for (var i = 0; i < colorDivs.length; i++) { colorDivs[i].style.backgroundColor = "#AA0000"; } 
     <div class="colDiv">Color 1</div> <div class="colDiv">Color 2</div> <div class="colDiv">Color 3</div> 


    Changing the background color of only one div-a, respectively, can be done at a specific index:

     var colorDivs = document.getElementsByClassName("colDiv"); colorDivs[1].style.backgroundColor = "#AA0000"; 
     <div class="colDiv">Color 1</div> <div class="colDiv">Color 2</div> <div class="colDiv">Color 3</div> 

      Your array

       var colorArray = [ document.getElementsByClassName('colDiv'), document.getElementsByClassName('colDiv'), document.getElementsByClassName('colDiv') ]; 

      consists of identical collections, obtained by sampling on the name of the same class. Accordingly, the code

       colorArray[i].style.backgroundColor = "#AA0000"; 

      refers to the nonexistent style property.

       function changeColor() { [...document.getElementsByClassName('colDiv')].forEach( item => item.style.backgroundColor = "lightgreen" ); } 
       <div class="colDiv">Color 1</div> <div class="colDiv">Color 2</div> <div class="colDiv">Color 3</div> <button onclick="changeColor()">Change Color</button>