I am trying to make an ‘opening hours’ table that highlights the current day for the user.
HTML:
<div id="Monday"> <h2> Mon</h2><h3>8am-9pm</h3></div>
<div id="Tuesday"> <h2> Tue</h2><h3>8am-9pm</h3></div>
<div id="Wednesday"> <h2> Wed</h2><h3>8am-9pm</h3></div>
<div id="Thursday"> <h2> Thu</h2><h3>8am-9pm</h3></div>
<div id="Friday"> <h2> Fri</h2><h3>8am-9pm</h3></div>
<div id="Saturday"> <h2> Sat</h2><h3>8am-9pm</h3></div>
<div id="Sunday"> <h2> Sun</h2><h3>8am-9pm</h3></div>
jQuery/Javascript/Idon’tevenknowanymore:
var d=newDate();
var day=d.getDay();
if (day == 1)
{
document.getElementById('Monday').style.color='#DB35B0'
}
else if (day == 2)
{
document.getElementById('Tuesday').style.color='#DB35B0'
}
else if (day == 3)
{
document.getElementById('Wednesday').style.color='#DB35B0'
}
else if (day == 4)
{
document.getElementById('Thursday').style.color='#DB35B0'
}
else if (day == 5)
{
document.getElementById('Friday').style.color='#DB35B0'
}
else if (day == 6)
{
document.getElementById('Saturday').style.color='#DB35B0'
}
else if (day == 0)
{
document.getElementById('Sunday').style.color='#DB35B0'
}
The trouble is that if I was going to change the color in the css I would use:
#Friday h3 {color:#DB35B0;}
which doesn’t seem to work in the Javascript like this:
else if (day == 5)
{
document.getElementById('Friday h3').style.color='#DB35B0'
}
I also tried:
else if (day == 5)
{
document.getElementById('Friday').children.style.color='#DB35B0'
}
But that did nothing.
So what do I do?
Is it possible to target the children of the divs and change their color?
Yes, there are various methods to retrieve descendant elements (such as
getElementsByTagName), butgetElementByIddoes not accept a CSS selector. The reason why[...].children.styledoes not work is that.childrenreturns aNodeList, i.e. a collection of nodes. You’d have to iterate over it or access it with the index of the node you want.I suggest a different, easier approach:
Create a CSS rule for the color, using a class:
Add that class to the current day:
This is less code and you can make changes to the style more easily.
Edit: I just saw that you tagged the question with jQuery. In that case, you can replace the last line with:
In contrast to DOM interface methods such as
getElementByIdorgetElementsByTagName, jQuery uses CSS selectors to get references to elements. You should have a look at the documentation if you intend to use it.