Changing the background colour of <body>

The following code is placed in the <head> section of the html file:

<script>

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

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

</script>

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.

The script is run by clicking a link. Here's the code:

<a href="javascript: changePageBackground()">Change page background</a>

Try the links below to see what happens.

Change page background | Change back

Note that the JavaScript code is placed "inline" i.e. within the anchor tag. Obviously, this is not ideal if we want to separate the behavioural layer from the structural layer.