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>
<title>Traffic Lights</title>
<script src=""></script>


<style type="text/css">
#traffic_light {
padding:10px 11px;
margin:0 auto;
border:2px solid #a1a1a1;

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

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

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

function colour_change() {

document.getElementByID("traffic_light").style.background = colour[i];

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