Implemented a deletion feature in the list, however, certain items that have been checked are not being removed

I am currently participating in the Wes Boros JS 30 challenge, where we created a list of our favorite foods. As part of the challenge, we were tasked with implementing a 'select all' function, an 'unselect all' function, and a 'delete' function. I managed to successfully create the 'select all' function, but I encountered an issue with the 'delete' function. When I try to delete items, some of them remain checked and require multiple clicks to delete. I incorporated local storage for this exercise.

If anyone could assist me and explain what I might be doing wrong, I would greatly appreciate it.

Here is a jsfiddle link for reference.

Here is the HTML setup:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>LocalStorage</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="wrapper">
    <h2>LOCAL TAPAS</h2>
    <p></p>
    <ul class="plates">
      <li>Loading Tapas...</li>
    </ul>
    <form class="add-items">
      <input type="text" name="item" placeholder="Item Name" required>
      <input type="submit" value="+ Add Item">
    </form>
    <input type="button" onclick="selectAll()" value="Select All"/>
    <input type="button" onclick="UnSelectAll()" value="Unselect All"/>
    <input type="button" onclick="deleteItem()" value="delete Item"/>
  </div>
</body>
</html>

Below is the JavaScript code:

  const addItems = document.querySelector('.add-items');
  const itemsList = document.querySelector('.plates');
  const items = JSON.parse(localStorage.getItem('items')) || [];
  
  
  
  //DELETE FUNCTION
  function deleteItem(){
      var boxes = document.getElementsByClassName('chk');
      var texts = document.getElementsByClassName('txt');
      for(var i = 0; i < boxes.length; i++){
        box = boxes[i];
        txt = texts[i];
        if(box.checked){
          box.parentNode.removeChild(box);
          txt.parentNode.removeChild(txt);
        }
      }
       
  }


  //SELECT ALL FUNCTION
  function selectAll(){
    var checkedItem = document.getElementsByName('item');
      for (var i = 0; i < checkedItem.length; i++) {
        if (checkedItem[i].type == 'checkbox')
            checkedItem[i].checked = true;
      }
  }
  
  //UNSELECT ALL FUNCTION
  function UnSelectAll(){
    var checkedItem = document.getElementsByName('item');
      for (var i = 0; i < checkedItem.length; i++) {
        if (checkedItem[i].type == 'checkbox')
            checkedItem[i].checked = false;
      }
  }

  //ADD ITEM FUNCTIO
  function addItem(e){
    e.preventDefault()
    const text = (this.querySelector('[name=item]')).value;

    const item = {
      text,
      done: false
    };
    items.push(item); 
    populateList(items, itemsList);
    localStorage.setItem('items', JSON.stringify(items));
    this.reset();
  }
//DISPLAY THE HTML FUNCTION
function populateList(plates =[], platesList) {
  platesList.innerHTML = plates.map((plate, i) => {
    return `
      <li>
      <input class="chk" type="checkbox" name="item" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} /> 
      <label class="txt" name="item" for="item${i}">${plate.text}</label>
      </li>
    `
}).join('');
}

function toggleDone(e){

 if(!e.target.matches('input')) return; 
 const el = e.target;
 const index = el.dataset.index;
 items[index].done = !items[index].done;
 localStorage.setItem('items', JSON.stringify(items));
 populateList(items, itemsList);
}
addItems.addEventListener('submit', addItem)
itemsList.addEventListener('click', toggleDone)
populateList(items, itemsList);


//DELETE ITEM EVENT HANDLER
itemsList.addEventListener('click', deleteItem);

Answer №1

The issue with the delete function not functioning correctly is due to the fact that when you utilize Node.childNodes, it returns a live NodeList. This implies that when you use removeChild on each element in the collection, the other elements are rearranged and the length of the list decreases, causing you to inadvertently skip some elements. To resolve this, you should convert the HTML collection to an array using Array.from.

function deleteItem(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
arrbox  = Array.from(boxes)
arrtext = Array.from(texts)
for(var i = 0; i < arrbox.length; i++){
var box = arrbox[i];
var txt = arrtext[i]; 
        if(box.checked){
          box.parentNode.removeChild(box);
          txt.parentNode.removeChild(txt);
        }
      }           
  }

For a demonstration, you can view the working version on this jsfiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React custom slider component is failing to meet expectations

I've been working on enhancing my React skills and building my portfolio. Instead of using a library, I opted to create a custom slider using the code below: const ProjectWrapper = styled.div` .container { transform: translateX(-$ ...

Retrieving multiple records from a database using a PHP object class

I have been attempting to implement the guidance provided in this particular inquiry: how can i return multiple database record from a class in OOP programming but unfortunately, I am encountering issues in getting it to function correctly. My objective i ...

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

I need to know how to use Axios to fetch data from multiple sources at the same time without any risk of the

Trying to initiate multiple axios operations simultaneously to fetch data from various sources at once using a loop leads to the received data getting intermingled and corrupted. Even creating distinct axios instances for each data source doesn't see ...

Hiding a parent DIV in JS based on specific content: Here's how

I need help figuring out how to hide multiple parent DIVs based on the content of a specific child DIV. Here's an example: <div class="report-per-day"> <div class="report-day">26 May 2022</div> <div class=" ...

Running Docker does not provide a means to access the application

I am currently developing an Express (nodejs) application that is running on port 3000, showcasing a simple hello world, and is hosted on a public github repository. So far, everything is running smoothly and the code itself looks like this: var express ...

Merge two arrays of objects in Ramda.js based on their shared ID property

I'm working with two arrays of objects: todos: [ { id: 1, name: 'customerReport', label: 'Report sent to customer' }, { id: 2, name: 'handover', label: 'Handover (in C ...

Troubleshooting NodeJS CORS issue in Vue project as localhost API calls fail

Having an ongoing project that utilizes a NodeJS/Express backend and a VueJS frontend, I am consistently encountering CORS errors: Cross-Origin Request Blocked: The Same Origin Policy restricts access to the external resource at https://localhost:8080/api ...

React - warning - Avoid using <Link> outside of a <Router> context

Warning: Invariant failed: It is not recommended to use <Link> outside of a <Router> Encountering this while attempting to write a test for a component where test("renders post list div ", () => { const posts = [ { created: ...

Using Flask and jQuery, learn how to toggle the visibility of a reply text box

After a break from using HTML/JavaScript, I find myself a bit puzzled about how to handle this. I'm working on creating a reddit-like clone with Flask. I've reached a point where I can add child comments to any comment and have them display nic ...

NodeJs ERROR: Module not found

When trying to launch an instance running ubuntu with express, I encountered a module not found error that does not occur on my Windows machine. Error Message: node:internal/modules/cjs/loader:1085 throw err; ^ Error: Cannot find module './src/c ...

When using jQuery, the search for the ID within an iframe may fail if the specified condition

I have a scenario where I need to dynamically generate an iframe and its corresponding id. Now, I need to check if the generated id already exists or not. This is what my code looks like: function createIframe(intxnId){ alert("The Id is : "+"$(&apo ...

Creating an HTML design with divs: a trio of pictures that adjusts in size to match the viewport (sl

As a newcomer to HTML and CSS, I find myself nearing completion of my website, with the final obstacle being an image slider in the background. The Challenge: The images are not perfectly centered within the viewport. Specifically, the first image needs ...

Tips for distinguishing individual submit buttons within a foreach loop

Here is my code snippet: <?php require_once 'core/init.php'; if($result = $db->query ("SELECT * from countries")) { if($count = $result->num_rows) { $rows = $result->fetch_all(MYSQLI_ASSOC); } ...

Choose components identified by a dot

If I have a simple script that displays an element based on the option selected, how can I handle periods in the values? For instance: <select id="my-selector"> <option value="cat.meow">Cat</option> <option value="dog.bark"> ...

Navigating through content on a screen can be accomplished in two

Is it feasible to incorporate both horizontal and vertical scrolling on a website using anchor tags? I recently created a website with horizontal scrolling for each main page. Within some of these main pages, there are subsections that I would like to hav ...

Send dropdown selections to a Javascript function and convert them into an array

Within my JavaScript function, I need to pass multiple selected values from dropdown menus and store them in a JavaScript array. Each time a value is selected and sent using the onchange() function, it should be added to the array. If the same value is sel ...

Automatically update certain attributes of an object with Spring MVC's auto-refresh feature

Currently, I have a table in JSP where I am populating all object attributes using Spring MVC. The backend is providing a list of DTO's which are then being added to the ModelView. In the JSP, we iterate through this DTO list and display it in the tab ...

Discovering the URL of an AJAX request on any given website

Is there a way to retrieve the URLs of AJAX requests that are sent by the current page on a website using a browser or another tool? ...

Unraveling the mystery: accessing the same variable name within a function in JavaScript

What is the best way to reference the same variable name inside a function in JavaScript? var example = "Hello"; console.log("outside function: " + example) function modifyVariable() { var example = "World!"; console.log("inside function: " + ex ...