1

Can't figure out how to modify the background color of the id someInput (which is a div). Code :


var number = Math.floor(Math.random() * 19) + 1;
var img1 = document.getElementById("img1");
var color1 = document.getElementById("someInput");
if (number == 1) {
    img1.src = "golconda.jpeg";
    color1.backgroundColor = 'red';
}

I successfully changed the image source for the id img1 but cannot change the background color. It works in CSS but I need to be able to change it in JS. Thanks for the help.

Tried other solutions online but didn't find anything.

Keyvan Soleimani
  • 606
  • 2
  • 4
  • 16
  • It should be `color1.style.backgroundColor` – Spectric Dec 17 '22 at 01:27
  • I changed it to that but it still doesn't work ☹️ – Lucas Ardelean Dec 17 '22 at 01:35
  • Is it because `number` isn't `1`? – Spectric Dec 17 '22 at 01:35
  • oh my god i have been trying to fix this for days. Thanks i am just a little dumb – Lucas Ardelean Dec 17 '22 at 01:38
  • 2
    The best way to change the background color of an element is to use Javascript to add or remove a class on that element, using a class name that describes the _state_ of a thing (or the _type_ of a thing) — for example `color1.classList.toggle('warning');` — and then apply the color in a stylesheet rule `.warning { background-color: red; }` – Stephen P Dec 17 '22 at 02:07
  • 1
    Does this answer your question? "[How to use JavaScript to change div backgroundColor](/q/1874560/90527)", "[How do I change the background color with JavaScript?](/q/197748/90527)" – outis Dec 17 '22 at 20:29

2 Answers2

1

backgroundColor is not a property of the html element color1. Html elements have a style property and backgroundColor is a property of style. Therefore your code should be like this:

var number = Math.floor(Math.random() * 19) + 1;
var img1 = document.getElementById("img1");
var color1 = document.getElementById("someInput");
if (number == 1) {
    img1.src = "golconda.jpeg";
    color1.style.backgroundColor = 'red';
}
André
  • 1,602
  • 2
  • 12
  • 26
0

you forget to put style there and it should be only background instead backgroundcolor.

color1.style.background = 'red';

  • why it should only be `background` instead `backgroundColor`? have you try `backgroundColor`? – Layhout Dec 17 '22 at 01:52
  • It shoudn't be necessarilly `background`, it can be `backgroundColor` and I would preffer to use it in this case, because is more specific. `background` is a shorthand for the following properties: `background-attachment`, `background-clip`, `background-image`, `background-origin`, `background-position`, `background-repeat`, `background-size`, and also `background-color`. They all could be defined together using only `background`. – André Dec 17 '22 at 22:59