I am trying to create a dynamic calendar. My first step is to add classes on to certain elements on click But, I ran into a problem along the way, classList.add(''); isnt working in the HTML. I could be doing something wrong I am not sure.
<ul class="days">
<li onClick='#'>1<li>
<li onclick="this.classList.add('active')">2</li>
<li onClick='#'>3</li>
<li onClick='#'>4</li>
<li onClick='#'>5</li>
<li onClick='#'>6</li>
<li onClick='#'>7</li>
<li onClick='#'>8</li>
<li onClick='#'>9</li>
<li onClick='#'><span class="active">10</span></li>
</ul>
CSS
/* Highlight the "current" day */
.days li .active {
padding: 5px;
background: #1abc9c;
color: white
}
I am trying to apply the onclick event to the number 2. But classList.add(''); isnt working. I'm sure theres a reason... any help would be appreciated.
It does not work because of your CSS rule or your DOM.
.days li .active applies the style on a child node of <li> with the class active, but using this.classList.add('active'), you add the class active on the <li> tag and the CSS rule should be .days li.active.
Your css selector is wrong, you need to remove the space between li and .active
like
.days li.active {
padding: 5px;
background: '#1abc9c';
color: white
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With