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

129
Visualizações
classList.remove y .add no funcionan por algún motivo

Al alternar el interruptor, recibo estos errores de la consola del navegador. Por alguna razón, no funciona y no puedo resolver por qué esto no funcionará. Recién estoy iniciando Javascript, así que no me enojes si hice algo estúpido.

 Uncaught TypeError: Cannot read properties of undefined (reading 'remove') at getValue (darkModeSwitch.js:8) at window.onload (index.html:17) Uncaught TypeError: Cannot read properties of undefined (reading 'add') at getValue (darkModeSwitch.js:13) at HTMLInputElement.onclick (index.html:26)

HTML:

 <div> <ul> <li><a href="kapcsolat/kapcsolat.html?version=691">Kapcsolat</a></li> <li><a href="projects/projects.html?version=691">Projektek</li> <li><a class="active" href="index.html?version=692">Kezdőlap</a></li> <li><label class="switch"><input onclick="getValue()" id="darkModeToggle" type="checkbox" checked><span class="slider round"></span></label><script src="scripts/darkModeSwitch.js"></script> </li> <h1 class="jayden" style="float: left;"><a class="jayden" href="index.html?version=-23424893215">jayden.hu</a></h1> </ul> </div>

CSS:

 .lightmode{ background-color: white; color: black; }

JavaScript:

 const body = document.body const anchor = document.getElementsByTagName("a"); const darkModeToggle = document.getElementById('darkModeToggle'); function getValue(){ if (darkModeToggle.checked) { body.classList.remove("lightmode") anchor.classList.remove("lightmode") console.log("checked") } else{ console.log("not checked") body.classList.add("lightmode") anchor.classList.add("lightmode") } };
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

El error se debe a que está intentando modificar classList en varios elementos a la vez; su variable de anchor contiene una matriz de elementos HTML (todos los anclajes) en lugar de un elemento específico.

Afortunadamente, debido a que CSS se conecta en cascada, no necesita cambiar la clase en ningún elemento además de su cuerpo. Simplemente dirija los elementos a como este en CSS para que hereden el color del body :

 function getValue() { document.body.classList.toggle("lightmode") };
 body { background-color: black; color: white; } .lightmode { background-color: white; color: black; } a { color: inherit; }
 <body> <ul> <li><a href="kapcsolat/kapcsolat.html?version=691">Kapcsolat</a></li> <li><a href="projects/projects.html?version=691">Projektek</a></li> <li><a class="active" href="index.html?version=692">Kezdőlap</a></li> <li><label class="switch"><input onclick="getValue()" id="darkModeToggle" type="checkbox" checked><span class="slider round"></span></label></li> <h1 class="jayden" style="float: left;"><a class="jayden" href="index.html?version=-23424893215">jayden.hu</a></h1> </ul> </body>

about 4 years ago · Juan Pablo Isaza Relatório

0

El problema no es del cuerpo sino anchor . Utiliza getElementsByTagName , que devuelve una Lista (arreglo) y no un solo elemento, aunque tenga a solo valor constante de anchor , será un arreglo con una longitud de 1.

Utilice querySelector por ID o seleccione el primer elemento document.getElementsByTagName("a")[0] -> no es realmente la mejor práctica.

O, si tiene varias etiquetas de anclaje, simplemente recorra sobre ellas

Vea abajo

 const body = document.body const anchor = document.querySelectorAll("a.jayden"); const darkModeToggle = document.getElementById('darkModeToggle'); function getValue() { if (darkModeToggle.checked) { body.classList.remove("lightmode") anchor.forEach(a => a.classList.remove("lightmode")) console.log("checked") } else { console.log("not checked") body.classList.add("lightmode") anchor.forEach(a => a.classList.add("lightmode")) } };
 .lightmode { background:blue } a.lightmode { color: white }
 <input onclick="getValue()" id="darkModeToggle" type="checkbox" checked /> <a class="jayden" href="#" >jayden.hu</a> <a class="jayden" href="#" >jayden.hu</a>

about 4 years ago · Juan Pablo Isaza Relatório

0

Anchor es una colección HTML que debe recorrerse en bucle:

 const body = document.body; const anchor = document.getElementsByTagName('a'); const darkModeToggle = document.getElementById('darkModeToggle'); function getValue(){ if (darkModeToggle.checked) { console.log("checked"); if(body.classList.contains("lightmode")){ body.classList.remove("lightmode") } for(var a=0;a<anchor.length;a++){ if(anchor[a].classList.contains("lightmode")){ anchor[a].classList.remove("lightmode"); } } } else{ console.log("not checked"); if(!body.classList.contains("lightmode")){ body.classList.add("lightmode") } for(var a=0;a<anchor.length;a++){ if(!anchor[a].classList.contains("lightmode")){ anchor[a].classList.add("lightmode"); } } } }
 .lightmode{ background-color: white; color: black; }
 <body> <div> <ul> <li><a href="kapcsolat/kapcsolat.html?version=691">Kapcsolat</a></li> <li><a href="projects/projects.html?version=691">Projektek</a></li> <li><a class="active" href="index.html?version=692">Kezdőlap</a></li> <li><label class="switch"><input onclick="getValue()" id="darkModeToggle" type="checkbox" checked><span class="slider round"></span></label><script src="scripts/darkModeSwitch.js"></script> </li> <h1 class="jayden" style="float: left;"><a class="jayden" href="index.html?version=-23424893215">jayden.hu</a></h1> </ul> </div> </body>

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