Search code examples
javascriptcssclasssettimeoutaddition

Different calculation on different calculator vs. one I scripted


On clicking div click, div three background color should change and then change back after a second. I have the code below which adds the class but the style doesn't show on the page.

let temp = document.querySelector('.three');
document.querySelector('.clickhere').addEventListener('click', () => {
  temp.classList.add('.select');
  console.log(temp);
  setTimeout(function() {
    temp.classList.remove('.select');
    console.log(temp);
  }, 1000);
});
.one {
  background-color: red;
}

.two {
  background-color: green;
}

.three {
  background-color: blue;
}

.select {
  background-color: black;
}

.clickhere {
  background-color: yellow;
}
<div class="one">
  ONE
</div>
<div class="two">
  TWO
</div>
<div class="three">
  THREE
</div>
<div class="clickhere">
  CLICK HERE
</div>


Solution

  • Updated your snippet, I only had to replace .select with select

    It's important to use period before the css classes only when selecting them with jQuery, when adding a new class and removing it, you should just write the name of it like you would inside the div tag.

    EDIT: I just saw that the question was already answered in the comments, credits to @maazadeeb! :)

    let temp = document.querySelector('.three');
    document.querySelector('.clickhere').addEventListener('click', () => {
      temp.classList.add('select');
      console.log(temp);
      setTimeout(function() {
        temp.classList.remove('select');
        console.log(temp);
      }, 1000);
    });
    .one {
      background-color: red;
    }
    
    .two {
      background-color: green;
    }
    
    .three {
      background-color: blue;
    }
    
    .select {
      background-color: black !important;
    }
    
    .clickhere {
      background-color: yellow;
    }
    <div class="one">
      ONE
    </div>
    <div class="two">
      TWO
    </div>
    <div class="three">
      THREE
    </div>
    <div class="clickhere">
      CLICK HERE
    </div>