Dat Boi
Dat Boi

Reputation: 683

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.

Upvotes: 3

Views: 619

Answers (4)

Maheer Ali
Maheer Ali

Reputation: 36594

The problem is not with classList the problem is the selector. .days li .active will select all the elements with class active which are inside <li> and li is inside element with class .days. There shouldn't be any space b/w li and .active

.days li.active

Upvotes: 0

Luke
Luke

Reputation: 2474

First of all your html is wrong for the first li element.

Second I think that maybe you are being misled by your css selector, since the 10th li element has a span inside whilst the 2nd doesn't. Check out this fiddle

https://jsfiddle.net/h6w7kaoy/1/

HTML:

 <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:

li.active, li span.active {
  color: blue;
  font-weight: bold;
}

If you try to remove li.active from the css selector, you will see that clicking on the li element will not affect the visuals (but the class is still being added ;-) )

Upvotes: 0

sjahan
sjahan

Reputation: 5960

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.

Upvotes: 2

R3tep
R3tep

Reputation: 12874

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 
}

Upvotes: 1

Related Questions