Home > Back-end >  Problem with for loop in a to-do website - JavaScript
Problem with for loop in a to-do website - JavaScript

Time:10-28

I have a problem with creating a for loop that will remove all my to-do lists. I've been coding for a week so this might sound like a really stupid question. The code is all in a function and is run by a buttons onclick attribute.

    let toDoList = document.querySelector(".to-do-list");
    let newListClass = document.getElementsByClassName('new-list');
    let newList = document.querySelector('.new-list');

    console.log(newList);
    console.log(newListClass.length);
    
    for (i = 0; i < newListClass.length; i  ) {
        newList.remove();
    }

CodePudding user response:

Two main options that I see:

// Option A) getting elements by class name
const newListClass = document.getElementsByClassName('new-list');
console.log(newListClass);

for (i = 0; i < newListClass.length; i  ) {
    newListClass[i].remove();
}

// Option B) getting elements with a selector, notice the "All"
const newListClass = document.querySelectorAll('.new-list');
console.log(newListClass);

for (i = 0; i < newListClass.length; i  ) {
    newListClass[i].remove();
}

You could also use forEach, but a classic for loop is always good

  • Related