1

I am attempting to create a to do list, and I want for the user to be able to press done, and the text gets crossed out. Here is the code I have so far.

HTML:

 <div class="task">
   <p class="taskText">Brush Teeth</p>
   <button class="edit">Edit</button>
   <button class="deleteTask">Delete</button>
   <button class="done">Done</button>
  </div>

<div class="task">
  <p class="taskText">Go to bed at 9</p>
  <button class="edit">Edit</button>
  <button class="deleteTask">Delete</button>
  <button class="done">Done</button>
</div>

JS:

// Iterate through all the task classes 
for (i = 0; i < task.length; i++){
    const done = task[i].getElementById("done"); // Select done button within the task class
    const taskText = task[i].getElementById("taskText"); // Select taskText within the task class

    // Cross out Text when User Hits Done Button
    done.addEventListener("click", function(){ 
        taskText.style.textDecoration = "line-through";
    });
}

I am getting an error:

app.js:57 Uncaught TypeError: Cannot read property 'addEventListener' of undefined at app.js:57

Owen
  • 178
  • 2
  • 7

1 Answers1

1

The id attribute should be unique within a document, so you should use classes instead and use .querySelector to obtain the elements.

const tasks = document.querySelectorAll('.task');
for (let i = 0; i < tasks.length; i++){
  const done = tasks[i].querySelector(".done"); // Select done button within the task class
  const taskText = tasks[i].querySelector(".taskText"); // Select taskText within the task class

  // Cross out Text when User Hits Done Button
  done.addEventListener("click", function(){ 
    taskText.style.textDecoration = "line-through";
  });
}
<div class="task">
 <p class="taskText">Brush Teeth</p>
 <button class="edit">Edit</button>
 <button class="deleteTask">Delete</button>
 <button class="done">Done</button>
</div>

<div class="task">
<p class="taskText">Go to bed at 9</p>
<button class="edit">Edit</button>
<button class="deleteTask">Delete</button>
<button class="done">Done</button>
</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80