I'd approach this a little differently. Change the HTML so that each element which could be targeted has a class in common. For example, in addition to having a class of 1
, or a class of 2
, these elements would also have a class of hour
too:
<div class="1 hour"></div>
<div class="2 hour"></div>
Then you can simply iterate over all .hour
elements first:
function hourTrack() {
$('.hour').css("background-color", "blue");
$(`.${moment().hour()}`).css("background-color", "red");
}
But also, classes should not start with numbers:
Which characters are valid in CSS class names/selectors?
a name must begin with an underscore (_), a hyphen (-), or a letter(a–z), followed by any number of hyphens, underscores, letters, or numbers.
So the classes of 1
, 2
, etc, aren't valid. Maybe change to:
<div class="hour-1 hour"></div>
<div class="hour-2 hour"></div>
and then use
function hourTrack() {
$('.hour').css("background-color", "blue");
$(`.hour-${moment().hour()}`).css("background-color", "red");
}
Depending in the HTML structure, you might be able to avoid the standalone .hour
classes if those elements can already be uniquely identified from a selector.