Changing the background colour of <body>

The following code is placed immediately before the closing </body> tag. The script works by manipulating the DOM, so placing it at the end of the file allows the DOM to complete before the script can run:


function changePageBackground(){
   var body = document.getElementsByTagName("body")[0]; = "#B2D526";

function changeBack(){
   var body = document.getElementsByTagName("body")[0]; = "#B9CAE0";

var change = document.getElementById("change");
change.onclick = changePageBackground;

var back = document.getElementById("back");
back.onclick = changeBack;


The above example uses two functions, one to make the change and one to change it back. In this case, we select the object we're interested in (the body element) by assigning it to a variable which we've called "body" (var body) and then use the variable to target that object for each property we want to change. In this case, we just change the background colour.

Each script is run by clicking an element which has an onclick event handler. In this case it's two spans with an id and styled to look like a button.

Try the "buttons" below to see what happens.

Change page backgroundChange back