简体   繁体   中英

How can you manipulate the style of a element within a certain class (JS)

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM