Hiding an element with JavaScript

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:


// This function sets the display property to "none"
function displayNone(){
   document.getElementById("box").style.display = "none";

// This function sets the display property to "block"
function displayBlock(){
   document.getElementById("box").style.display = "block";

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

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


The above example uses two functions, one to make the change and one to change it back. This isn't the most efficient way of doing it but it is the simplest.

The object (element) you want to change is identified by an ID. Remember, this is unique to that object. In this example, the element containing the code above has been given the ID "box" and the opening tag looks like this: <pre id="box">.

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.