2

I am a beginner and I want to make color game as a project. The html contains six grids but the javascript is showing the error?

var colors = [
 "rgb (255, 0, 0)",
 "rgb (255, 255, 0)",
 "rgb (255, 0, 255)",
 "rgb (0, 255, 255)",
 "rgb (0, 255, 0)",
 "rgb (0, 0, 255)",
]

var squares = document.querySelectorAll(".square");

for (var i = 0; i < squares.length; i++){
 squares[i].style.background-color = colors[i];
}
Ero-sennin
  • 45
  • 5
  • 7
    `style.background-color` is invalid syntax for accessing a property name with dashes in it – Patrick Evans Feb 03 '18 at 12:55
  • This question is not duplicated completely as there is error in `colors` array where the style will not apply as there is white space in `rgb (255, 0, 0)` after `rgb` which it shouldn't. – Ankit Agarwal Feb 03 '18 at 13:04

2 Answers2

1

It is throwing an error because style.background-color has a dash in it and it is not valid . You can use background instead

for (var i = 0; i < squares.length; i++){
 squares[i].style.background  = colors[i];
}

or backgroundColor as follows,

 squares[i].style.backgroundColor = colors[i];
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

There are two issues in your code:

  • There should not be any white space in rgb (255, 0, 0). The color value should be rgb(255, 0, 0) where there is no space after rgb

  • Second issue is the background-color which should be backgroundColor.

var colors = [
 "rgb(255, 0, 0)",
 "rgb(255, 255, 0)",
 "rgb(255, 0, 255)",
 "rgb(0, 255, 255)",
 "rgb(0, 255, 0)",
 "rgb(0, 0, 255)",
]

var squares = document.querySelectorAll(".square");

for (var i = 0; i < squares.length; i++){
 squares[i].style.backgroundColor = colors[i];
}
<div class='square'>Color 1</div>
<div class='square'>Color 2</div>
<div class='square'>Color 3</div>
<div class='square'>Color 4</div>
<div class='square'>Color 5</div>
<div class='square'>Color 6</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62