Lesson Ten: The getElementById() Function/Method


  1. Your current JavaScript code should look like this:
    var event1;
    event1 = "488 Million Years Ago the Mollusks Appeared";
    var event2 = "250 Million Years Ago the Dinosaurs Appeared";
    var event3 = "65 Million Years Ago - Age of the Mammals";
    var event4 = "60 Million Years Ago - The Primates";
    var event5 = "5.2 Million Years Ago - The Hominids";
    var eventchoice;
    function historyevents(eventnumber) {
    eventchoice = eventnumber;
    if (eventchoice == 1) {
    button = document.getElementById("b1");
    button.value = event1; }
    else if (eventchoice == 2) { document.write(event2); }
    else if (eventchoice == 3) { document.write(event3); }
    else if (eventchoice == 4) { document.write(event4); }
    else { document.write(event5); }

  2. The getElementById() is a property of the document object. Properties of objects can be things like: names, ages, dates and so forth. However, properties can also be functions. Functions of objects are refered to as methods. So technically getElementById() is a method of the document object.
  3. In lesson nine you entered this code to your JavaScript file:
    button = document.getElementById("b1");
    button.value = event1; }

  4. The first line of code establishes the fact that you are refering to the button with the id of b1. The method getElementById is very descriptive - it performs the task of getting the element designated by the parameter in the () parenthesis. In this case it gets a reference to the button in your HTML file with the id of b1.
  5. The second line of code writes the value of the variable event1 to the value property of the button object.
  6. Now add five more buttons to your HTML file as shown below:
    <input type="button" id="b2" value="Click the Button to see Event Two" onclick="historyevents(2);">
    <input type="button" id="b3" value="Click the Button to see Event Three" onclick="historyevents(3);">
    <input type="button" id="b4" value="Click the Button to see Event Four" onclick="historyevents(4);">
    <input type="button" id="b5" value="Click the Button to see Event Five" onclick="historyevents(5);">
    <input type="button" id="b6" value="Reset" onclick="location.reload();">
  7. You're already familiar with the properties of the buttons in lines one through four, however, line five adds something new. This button calls the location.reload() method. The location.reload() method reloads the page which resets all variables and properties. This will be especially helpful when you begin the development of training challenges. You want to allow your students the opportunity to start over.
  8. In the next lesson you'll have the opportunity to see the CSS and JavaScript code that was used to create the sample below. Try to duplicate the sample without looking ahead.
  9. Test your program with the new code. Your page should look like this: Sample

Lesson Eleven: The Current Code