xTom xTom - 1 year ago 77
CSS Question

Javascript button click change background

The background color is not changing when I press the button. What am I doing wrong?

var body = document.getElementsByTagName("body");
var bgbutton = doucument.getElementById("bgchange");
bgbutton.onclick = function() {
body.style.background-color = "green";

body {
width: 600px;
margin: 0 auto;
background-color: #FF9500;
padding: 0 20px 20px 20px;

<div id="wrapper"></div>
<button id="bgchange"></button>

Answer Source

document.getElementsByTagName returns a node list, so you need to pick an element from that with [0]:

var body = document.getElementsByTagName("body")[0];

However, there is a specific property you can use instead:

var body = document.body;

Also you have a spelling mistake in the line that follows:

var bgbutton = doucument.getElementById("bgchange");

... should be document...

And, the style attribute names are in camelCase when written in JavaScript:


... as opposed to how they are written in CSS (background-color).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download