Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
Need to add a class when a checkbox is checked in javacript

i'm challenging myself by creating a website that have a dark and light mode.

When the checkbox is checked, it add the class "light" on the header for example, dark is default mode.

I've created a script but i didn't found the solution and why it's not working, can someone help me in this direction?

Here is my code:

let header = document.getElementsByClassName('header');
let switcher = document.querySelector('#switch');

switcher.addEventListener('click',function(){
    if(this.checked){
        header.classList.add('light');
    }
    else{
     header.classList.remove('light');
     }
})
<div class="header ">
            <div class="title-section">
                <h1>Social Media Dashboard</h1>
                <p>Total Followers: 23,004</p>
            </div>
            <div class="switchbtn">
                <label for="switch" id="switchlabel">Dark Mode</label>
                <input type="checkbox" name="switch" id="switch">
            </div>
</div>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Almost, you were just missing an index for document.getElementsByClassName. This returns an array of matching items. Because you've only got one you can just get the first in the array no problem.

So all you need to change is:

document.getElementsByClassName to document.getElementsByClassName[0]

and you're good to go!

let header = document.getElementsByClassName('header')[0];
let switcher = document.querySelector('#switch');

switcher.addEventListener('click',function(){
    if(this.checked){
        header.classList.add('light');
    }
    else{
     header.classList.remove('light');
     }
})
<div class="header ">
            <div class="title-section">
                <h1>Social Media Dashboard</h1>
                <p>Total Followers: 23,004</p>
            </div>
            <div class="switchbtn">
                <label for="switch" id="switchlabel">Dark Mode</label>
                <input type="checkbox" name="switch" id="switch">
            </div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can access the HTML of the header entering inside the collection, so try using

 getElementsByClassName('header')[0].

I prefer using querySelector() for adding and removing classes, it's simpler.

about 4 years ago · Juan Pablo Isaza Relatório

0

I made some changes to the code so that you can have a base and start working. I changed getelementsbyclassname to getElementById since the first one will return an array of all elements with this class name.

let header = document.getElementById("header");
let switcher = document.querySelector('#switch');

switcher.addEventListener('click',function(){
    if(this.checked){
      header.classList.add("dark");
    }
    else{
      header.classList.remove("dark");
    }
})
.dark {
  color: white;
  background: black;
}
<div id="header">
            <div class="title-section">
                <h1>Social Media Dashboard</h1>
                <p>Total Followers: 23,004</p>
            </div>
            <div class="switchbtn">
                <label for="switch" id="switchlabel">Dark Mode</label>
                <input type="checkbox" name="switch" id="switch">
            </div>
</div>

Also, I made it white as default and dark when you click. Hope it helps.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda