Robert Clarke Robert Clarke -4 years ago 175
Javascript Question

How do I change the background-color CSS with Javascript?

I was wanting to change the background-color in my CSS code by using a button with Javascript. I have tried things such as document.getElementByID("").style.background = colour. This didn't work, presumably because I was selecting the HTML element rather than the ID, where the CSS infromation is stored. I also tried JQuery. I tried $("#traffic_light").css("background-color", "green"). This also didn't work, but it may have been because I didn't use the correct selector at the start. If anyone does know the selector to select the CSS style for an ID then please tell me. Anyway here's my code:

<!DOCTYPE html>
<html>
<head>
<title>Traffic Lights</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>


<style type="text/css">
#traffic_light {
width:200px;
height:200px;
padding:10px 11px;
margin:0 auto;
border:2px solid #a1a1a1;
border-radius:150px;
background-color:green;
}
</style>

<div id="traffic_light"></div>

<button type="button" onclick="colour_change()">Change Lights</button>

<script>
var colour = ["green", "orange", "red"];
var i = 0;
document.getElementByID("traffic_light").style.background = colour[i];

function colour_change() {
i++;

document.getElementByID("traffic_light").style.background = colour[i];
};
</script>
</body>
</html>

Answer Source
document.getElementById("traffic_light").style.backgroundColor = colour[i];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download