Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't classList.add work for html onClick

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.

like image 298
Dat Boi Avatar asked May 07 '26 13:05

Dat Boi


2 Answers

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.

like image 85
sjahan Avatar answered May 10 '26 03:05

sjahan


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 
}
like image 30
R3tep Avatar answered May 10 '26 03:05

R3tep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!