Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
Checking a checkbox and applying the style to the corresponding input value

I'm creating a todo list in vanilla JavaScript. Right now, I'm trying to apply a style to a todo when the corresponding checkbox is checked.

toDoContainer.addEventListener("change", function(e) {
    const tgt = e.target;
    if (tgt.classList.contains("checkbox")) {
      let toDo = tgt.closest("input").classList.contains("input");
      if (toDo.value !== "") {
          toDo.style.opacity = "50%";
      }
    }
  });

As it stands, nothing is happening visibly and I'm not getting an error.

I'm using the closest() method because the checkbox and the todo are both inputs that are right next to eachother in the DOM.

Before I was using this code -

allCheckboxes.forEach(box => {
    box.addEventListener("change", () => {
        if (box.checked) {
            for (let toDo = 0; toDo < allToDos.length; toDo++) {
                if (allToDos[toDo].value) {
                    allToDos[toDo].style.textDecoration = "line-through";
                    allToDos[toDo].style.opacity = "50%";
                }
            }
        }
        else {
            console.log("cat");
            for (let toDo = 0; toDo < allToDos.length; toDo++) {
                if (allToDos[toDo].value) {
                    allToDos[toDo].style.textDecoration = "none";
                    allToDos[toDo].style.opacity = "100%";
                }
            }
        }
    })
})

I was able to apply the styles to the inputs but only when the first checkbox in the node list was checked. Checking the checkbox also applied the styles to all of the todos in the DOM, not just the corresponding one which is what I want.

Another quirk that I've just noticed is that when I look at dev tools to see if it's logging the checkboxes it shows an empty node list - [] when there are multiple checkboxes visible.

document.getElementById("add").addEventListener("click", () => {
    console.log(allCheckboxes);
});

How can I apply styling to only the corresponding todo when a checkbox is checked?

*** EDIT - https://codepen.io/harri-greeves/pen/LYLEKNj ***

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I'm using the closest() method because the checkbox and the todo are both inputs that are right next to each other in the DOM.

The closest method searches the element itself and then it searches the element's ancestors, moving up the dom tree.

I don't think .closest can be used to target siblings.

https://api.jquery.com/closest/

about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem is on line:

const allCheckboxes = toDoContainer.querySelectorAll("[type=checkbox]");

querySelector returns not living html collection. It means that it will not include dynamically added todos.

The better way is to listen parent node: todoContainer and then manipulate state.

about 4 years ago · Juan Pablo Isaza Denunciar

0

add this function

function ChangeOpacity() {
let checkbox = document.getElementsByClassName("checkbox");
  let input = document.getElementsByClassName("input");
  for (let i = 0; i < checkbox.length; i++) {
   checkbox[i].addEventListener("change",()=>{
     if (checkbox[i].checked == true) {
       if (input[i].value) {
         input[i].style.opacity = "50%"
         input[i].style.textDecoration = "line-through"
       }
       else{
        input[i].style.opacity = "100%"
        input[i].style.textDecoration = "none"
       }
     } else {
      if (input[i].value) {
        input[i].style.opacity = "50%"
        input[i].style.textDecoration = "line-through"
      }
      else{
       input[i].style.opacity = "100%"
       input[i].style.textDecoration = "none"
      }
     }
   

   })
    
  }
}
ChangeOpacity()

and then call this function to the createToDo function everything should work fine and its cleaner this way

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda