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

281
Visualizações
Can't set attribute of document.documentElement;

I have following code to set the dark mode for the document.body

function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
}
.dark-mode {
  background-color: black;
  color: white;
}
<label class="switch">
  <input onclick="myFunction()" type="checkbox">
  <span class="slider round"></span>
</label>

If I set the document.body to document.documentElement it does not work. Does someone know how to fix it for the root element of the HTML? I also tried document.querySelector(":root");.

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

0

So the code as you have it seem to be working fine, both document.body and document.documentElement, so the issue might be related on where and how you are importing de CSS.

With document.documentElement

<style>
    .dark-mode {
  background-color: black;
  color: white;
}
</style>
<label for="toggle" class="switch">
    Toggle
    <input onclick="myFunction()" type="checkbox">
    <span class="slider round"></span>
  </label>
  
  
  <script>
    function myFunction() {
      var element = document.documentElement;
      element.classList.toggle("dark-mode");
    }
  </script>

With document.body

<style>
    .dark-mode {
  background-color: black;
  color: white;
}
</style>
<label class="switch">
    Toggle
    <input onclick="myFunction()" type="checkbox">
    <span class="slider round"></span>
  </label>
  
  
  <script>
    function myFunction() {
      var element = document.body;
      element.classList.toggle("dark-mode");
    }
  </script>

But also as a general recommendation de input shouldn't be wrapped in the label tag.

<style>
    .dark-mode {
  background-color: black;
  color: white;
}
</style>
<label for="toggle" class="switch">
    Toggle
  </label>
  <input id="toggle" name="toggle" onclick="myFunction()" type="checkbox">
    <span class="slider round"></span>
  
  
  <script>
    function myFunction() {
      var element = document.body;
      element.classList.toggle("dark-mode");
    }
  </script>

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