How to remove a innerHTML li with a class name using JavaScript

45 views Asked by At

I am creating a Todo App and I am still new to JavaScript, I have a problem with removing completed tasks with class (todos)li.checked found in the innerHTML from user input.

<div class="todo-container">
<ul class="todo-list">
*/<li class="checked">completed task</li>


<li>Uncompleted task</li>*/
</ul>
</div>
<div class="btn" onclick="deletecompletedTask()> deleteAll</div>



JS

const btn = document.querySelector(".btn");
const todoContainer = document.querySelector('.todo-container');
const todolist = document.querySelector('.todo-list);

//Delete completed task
function deletecompletedTask(){
todoContainer.innerhtml = document.getElementByClassName('checked');
todoContainer.removeChild(todoContainer.firstChild);
}
1

There are 1 answers

0
JW Yap On

Explanation

Hi, I think to achieve what you want, you shall not set the innerhtml, but to use the remove function.

Here're some modifications to your script, which it'll first look for all elements with class tagged with "checked". Then, we will use a "forEach" loop to remove all of them.

// loop through all the .checked element and remove them 
function deletecompletedTask() {
  document.querySelectorAll(".checked").forEach(function(e) {
    e.remove();
  });
}

// add event listener to delete button
let btn = document.getElementById("deleteBtn").addEventListener("click", function() {
    deletecompletedTask();
});
<div class="todo-container">
<ul class="todo-list">
<li class="checked">completed task</li>


<li>Uncompleted task</li>
</ul>
</div>

<button id="deleteBtn" class="btn"> deleteAll</button>