Home > Enterprise >  How to use javascript get element to modify background color of div element?
How to use javascript get element to modify background color of div element?

Time:12-17

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.

CodePudding user response:

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';
}

CodePudding user response:

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

color1.style.background = 'red';

  • Related