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

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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