Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to remove selected li from an ul in javascript

i created a todolist and a button which removes checked tasks from an ul but it removes all li’s from an ul.

      <div class="container mt-5">
      <ul class="list-group" id="tasks"> </ul>

      <div class="col">
        <button type="button" class="btn btn-primary" id="delchecked">Delete done tasks</button>
      </div>
        function addTask() {

        const li=document.createElement("li");
        li.className="list-group-item";
        tasks.appendChild(li);

        const checkBox=document.createElement("input")
        checkBox.className="form-check-input me-1 fa-pull-right"
        checkBox.type="checkbox"
        checkBox.name="chk"
        li.appendChild(checkBox);
        checkBox.id="checkBox";

        const delchecked=document.querySelector("#delchecked");
        delchecked.addEventListener("click",deleteCheckedItem);
        }
     

         function deleteCheckedItem(){
          var k=document.getElementsByName('chk');  
          for(var i=0; i<k.length; i++){  
            if(k[i].checked==true) 
            tasks.removeChild(li);
          } 
        }  

i want to remove selected li from an ul but code above removes all "li".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

try this:

function deleteCheckedItem() {
var checkboxes = document.getElementsByName('chk');
for (var i = checkboxes.length - 1; i >= 0; i--) {
  if (checkboxes[i].checked) {
    var listItem = checkboxes[i].parentNode;
    listItem.parentNode.removeChild(listItem);
  }
}
}


 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading