Step 7
-
We must calculate and display the wake up hours when 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>
- Here is a sample code to access and update the content of this
<p>
element:
let hours = // get the <p> element
hours.innerText = // string containing hours
- Similar to how we accessed the output
<div>
, we can access this<p>
element by giving it a class attribute such as<p class="hours">
let hours = document.querySelector('.hours');
hours.innerText = "placeholder for hours!";
- We can, alternatively, give it an ID attribute
<p id="hours">
:
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 use ID attribute on the
<p>
element; update thehandleOnClickEvent
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 usequerySelector('#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 theindex
page in the browser. Notice when you click onzzz
button, the output is displayed but the hours are now replaced withplaceholder for hours!