Step 9

  • We must calculate and display the wake-up hours when a user clicks on the zzz button. Let's focus on the second part: displaying the hours.

  • At the moment, there is a <p> element that holds the hours:

<p>11:44 PM or 1:14 AM or 2:44 AM or 4:14 AM or 5:44 AM or 7:14 AM</p>
  • Let's distinguish this <p> element from other such elements by giving it an ID attribute.
<p id="hours">11:44 PM or 1:14 AM or 2:44 AM or 4:14 AM or 5:44 AM or 7:14 AM</p>
  • Here is a sample code to access and update the content of this <p> element:
let hours = document.getElementById('hours');
hours.innerText = "Placeholder for hours!";
  • The ID attribute specifies a unique id for an HTML element.

The ID must be unique within the HTML document, although your webpage will still work if you use the same ID for multiple elements!

  • The getElementById() method returns the element that has the ID attribute with the specified value.
  • Let's put it all together; update the handleOnClickEvent function as follows:
<script>
  function handleOnClickEvent() {
    let output = document.querySelector('.output');
    output.style.display = 'block';

    let hours = document.getElementById('hours');
    hours.innerText = "Placeholder for hours!";
  }
</script>

Instead of getElementById('hours') we could use querySelector('#hours'). The difference between the two is not important to us now, but if you are interested, see this stack-overflow query

  • Save the index.html file; refresh the index page in the browser. Notice when you click on zzz button, the output is displayed, but the hours are now replaced with a Placeholder for hours!.