Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
classList.toggle() not adding the class

I'm trying to make a switch change the background color of a div using classList.toggle, but it isn't working and I don't know why, even though it's probably very simple. Can someone clarify this to me, please?

var toggle = document.getElementById('switch')

toggle.onclick = function() {
  document.getElementById('testDiv').classList.toggle('test')
}
#testDiv {
  width: 250px;
  margin: auto;
  margin-top: 16px;
  background-color: white;
}

.test {
  background-color: black !important;
}
<label class="switch" id="switch" onclick="myFunction()">
  <input type="checkbox">
  <span class="slider round"></span>
</label>

<div id="testDiv">
  <p>
    plain text
  </p>
</div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can call the myFunction when the user clicks the checkbox. Fixed the CSS file to place !important in proper position.

function myFunction(){
    document.getElementById('testDiv').classList.toggle('test');
}
#testDiv {
  width: 250px;
  margin: auto;
  margin-top: 16px;
  background-color: white;
}

.test {
  background-color: black !important;
  color: white;
}
<label class="switch" id="switch" for="change_bg">Change background</label>
<input type="checkbox" id="change_bg" onclick="myFunction()">

<div id="testDiv">
  <p>
    plain text
  </p>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!