1

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
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Kevin Grant
  • 138
  • 9
  • 3
    `getElementsByClassName` returns an array-like object so you'd need to specify which _one_ to change, e.g. `getElementsByClassName('open')[0].innerHTML` – j08691 Jan 07 '19 at 18:11
  • https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return – epascarello Jan 07 '19 at 18:12
  • use `document.querySelector('.open')` – Bibberty Jan 07 '19 at 18:12
  • 1
    Unrelated, but keep in mind that the `Date` object in JS just gets the time from the computer running the code. if someone in a different time zone views this website, it might be inaccurate – Chris Barr Jan 07 '19 at 19:26

2 Answers2

4

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>
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
4

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');
Jay Mason
  • 446
  • 3
  • 17