Home > Blockchain >  I am having problems with a my function to delete html elements. (First time posting, please be nice
I am having problems with a my function to delete html elements. (First time posting, please be nice

Time:02-14

I am a begginer programmer and I am working on my first small project. I decided to make a notes app. It is basically completed, except that I wanted to have a button to delete all completed task and I am having problems with it. Basically, it works on localStorage, where I store the task name as a key, wit ha value of either 0(incomplete) or 1(completed). In this last function, I want to delete all the tasks with localStorage value of 1. This is my code. Once I run it, I am having problems with deleting all of the li elements. some get deleted, some not. In the console, I see two errors of tableChild not being declared. It seems weird.

    document.querySelector(".btn-delete-completed").addEventListener("click", function () {
    let children = listOfTasks.children; /*takes an ul element (listOfTasks) and selects its child elements*/
    let arrayLenght = children.length; /*variable to see the lenght of the created arrray*/
    let tableChild = 0; /*creates a variable that will be redeclared in the loop dynamically*/
    for (let i = 0; i < arrayLenght; i  ) { /*for loop that takes a stative arrayLenght instead of dynamic one(since we will be deleting elements)*/
      tableChild = children[i]; /*redeclares a tableChild variable to a single li with the text that is a key to localStorage*/
      if (localStorage.getItem(tableChild.textContent) == 1) {/*Checks for the value in localStorage, getItem() uses the key that is text of the selected element*/
        tableChild.remove();/*removes the element from html*/
        localStorage.removeItem(tableChild.textContent); /*removes element from localStorage*/
      }
    }
  });

Here it is. I hope the documentation is good enough. As I said, I am just a begginer and I am posting here first time. If you have any questions, I will gladly answer them in the comments! Once again sorry if I messed something up in this post.

Thanks in advance!

CodePudding user response:

When you delete elements from an array, its length changes. This is not accounted for in your code.

I find it easiest to iterate backwards in that case:

for (let i = children.length - 1; i >= 0; i--){
//...
  • Related