Issue
When I click on any checkbox of added to-dos css property applies only on the first element.
const input = document.querySelector("#input");
const container = document.querySelector(".to_dos_container");
input.addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
    add = `<div class="task_container">
    <input type="checkbox" class='done'>
    <p class='task'>${input.value}</p>
  </div>`;
    container.insertAdjacentHTML("afterbegin", add);
    input.value = "";
    lineThrough()
  }
});
function lineThrough() {
  var checked = document.querySelectorAll(".done");
  checked.forEach((c) => {
    c.addEventListener("click", (p) => {
      var task = document.querySelector(".task");
      if (c.checked) {
        task.style.textDecoration = "line-through";
        task.style.color = "gray";
      } else {
        task.style.textDecoration = "unset";
        task.style.color = "unset";
      }
    });
  });
}<div class="text_area">
  <input type="checkbox" class="disabled" disabled>
  <input id="input" placeholder="Create a new todo..." type="text">
</div>
<div class="to_dos_container">
</div>I want when I click on checkbox of added to-dos css property should apply on its respective to to-do.
Solution
document.querySelector(".task") selects the first element with the class .task. You need to use nextElementSibling to select the element that follows the element with class .task, since there is only two sibling elements inside the div it will select the corresponding checkbox.
Change this
var task = document.querySelector(".task");
To this
var task = c.nextElementSibling;
Answered By - Jacob
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.