Reputation: 138
I am simply trying display an 'open' or 'closed' text inside an element with the class name open
if the time is between a
and b
.
I tried the following but nothing is displayed on the .open
element. What is wrong with this code?
const hours = new Date().getHours()
const openHours = (hours >= 8 && hours < 17) ? 'Open' : 'Closed'
document.getElementsByClassName('open').innerHTML = openHours
Upvotes: 1
Views: 175
Reputation: 16301
If there is only one element in your page with the classname open
, just use querySelector()
instead like this:
const hours = new Date().getHours()
const openHours = (hours >= 8 && hours < 17) ? 'Open' : 'Closed'
document.querySelector('.open').innerHTML = openHours
<p class="open"></p>
But if there is more than one element with the class name open
that you want to insert the ternary result to, you can retrieve all the elements using querySelectorAll()
instead and then use forEach()
to access each element like this:
const hours = new Date().getHours()
const openHours = (hours >= 8 && hours < 17) ? 'Open' : 'Closed'
document.querySelectorAll('.open').forEach(x => {
x.innerHTML = openHours
// here, x is every div with the `open` class name that you have queried above.
})
<p class="open"></p>
<p class="open"></p>
Upvotes: 4
Reputation: 470
The function getElementsByClassName returns multiple elements. Classes are designed to be applied to multiple objects. One option to solve this would be to get the first element in the array.
Here is an example of that:
var elements = document.getElementsByClassName('open');
elements[0].innerHTML = openHours
(Shorthand version of this would be using querySelector, although keep in mind that querySelector is a lot slower than the built in DOM functions - and its not supported in early version's of IE or FireFox. )
Looping through each of the elements in the classes is another option as well:
var elements= document.getElementsByClassName("open");
for(var i = 0; i < elements.length; i++)
{
elements[i].innerHTML = openHours
}
Otherwise (what I would recommend, since you only need one object), is giving the object an ID instead of a class.
<div id="openStatus"></div>
document.getElementById('openStatus');
Upvotes: 4