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

130
Views
Cómo apuntar a ".switch-field input:checked" para realizar cambios en las propiedades de CSS con JavaScript

¿Cómo puede Javascript cambiar las propiedades CSS de input:checked

CSS

 .switch-field input:checked + label { background-color: #018786; color:white; box-shadow: none; }

Digamos que quiero cambiar su color de fondo-

JS

 document.getElementsByClassName("switch-field input:checked")[0].style.background= #4400ff;

¿Cómo puedo apuntar a esa "clase" específica con "entrada verificada"?

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

0

Puede usar querySelector para un solo elemento o querySelectorAll para varios elementos. Puede usar la consulta CSS en eso.

 document.querySelector("switch-field input:checked").style.background = "#4400ff";
about 4 years ago · Juan Pablo Isaza Report

0

Explicación

Básicamente los pasos que debes seguir son

  1. Borrar todas las propiedades de estilo de fondo de la etiqueta
  2. Seleccione toda la input:checked + label (ese es el elemento que tiene la propiedad de color de fondo)
  3. Recorra todas las etiquetas obtenidas
  4. Cambia el color de fondo a lo que quieras

Tengo que estar al tanto de

  1. Cambiar la propiedad de fondo a través de javascript no la cambiará automáticamente cuando la entrada no esté marcada
  2. Deberá ejecutar una función de borrado/actualización en el evento onChange de la input para asegurarse de que establece los fondos correctamente al verificar y desmarcar la entrada

Sugerencias

  1. Usa las clases input:checked + label y input + label de CSS para agregar tus fondos
  2. Siempre trate de evitar la manipulación de estilos de JavaScript, va en contra de la convention y, por lo general, se considera una mala práctica si se puede evitar.

Solución

 function clickHandle() { // Clear all the labels background style property to ensure it resets to the css class background property clearLabelBackground(); // Get all the labels (not input) based on the css input:checked flag // We are getting the label because that if the element which has the background color property you want to change var selectedLabels = document.querySelectorAll("input:checked + label"); // Loop through each of the fetched labels selectedLabels.forEach((label)=>{ // Change the background color style label.style.background="#4400ff"; }); } function clearLabelBackground() { // Get all the labels (not input) regardless of the selection // We are getting the label because that if the element which has the background color property you want to change var selectedLabels = document.querySelectorAll("input + label"); // Loop through each of the fetched labels selectedLabels.forEach((label)=>{ // Remove the background color style label.style.background=""; }); }
 .switch-field input:checked + label { background-color: #018786; color:white; box-shadow: none; }
 <div class="switch-field"> <input type="checkbox"/> <label>Item 1</label> </div> <div class="switch-field"> <input type="checkbox"/> <label>Item 2</label> </div> <div class="switch-field"> <input type="checkbox"/> <label>Item 3</label> </div> <div class="switch-field"> <input type="checkbox"/> <label>Item 4</label> </div> <button onclick="clickHandle()">Change BG</button>

He comentado el código javascript, si necesita más aclaraciones, no dude en comentar esta respuesta

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!