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>
12:15 AM<br />
1:45 AM<br />
3:15 AM<br />
4:45 AM<br />
6:15 AM<br />
7:45 AM
</p>
- Let's distinguish this
<p>
element from other such elements by giving it an ID attribute.
<p id="hours">
12:15 AM<br />
1:45 AM<br />
3:15 AM<br />
4:45 AM<br />
6:15 AM<br />
7:45 AM
</p>
- Here is a sample code to access and update the content of this
<p>
element:
let hours = document.getElementById('hours');
hours.innerHTML = "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.innerHTML = "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 with aPlaceholder for hours!
.