Loop "for" does not scroll through all list items

Asked

Viewed 49 times

0

I have a problem with the following function:

function limpaLista() {
    var lista = document.getElementById('resposta');
    var itens = document.getElementsByClassName('Repos');
    for (item of itens) {
        lista.removeChild(item);
    }
}

She should totally delete a list of names, but for some reason she deletes half of the list just at each run.

  • Place a console.log and check if the number of items and the list are really correct, and also check that all items actually contain this Repos class.

  • follows the result: 
function limpaLista() {
 var lista = document.getElementById('resposta');
 var itens = document.getElementsByClassName('Repos');
 console.log(itens.length);
 console.log(itens);
 for (item of itens) {
 lista.removeChild(item);
 }
 console.log(itens.length);
 console.log(itens);
}


  • Solved with the answer below, vlw

1 answer

3


The logic isn’t wrong, but there’s a trap in that code.

The return of the method getElementsByClassName is a HTMLCollection, a "live" list that is updated as you add or remove elements in the DOM. When removing these elements from the DOM, you are removing them from your list as well, and you need to be careful when iterating over a list that is being reduced.

My suggestion is to transform this HTMLCollection in a common array before removing items, thus, although elements are removed from the DOM, at least the structure of your list remains integrated during iteration:

function limpaLista() {
    var lista = document.getElementById('resposta');
    var itens = Array.from(document.getElementsByClassName('Repos'));
    for (item of itens) {
        lista.removeChild(item);
    }
}

Or alternatively make a while to remove all items while they exist:

function limpaLista() {
    var lista = document.getElementById('resposta');
    var itens = document.getElementsByClassName('Repos');
    while (itens.length) {
        lista.removeChild(itens[0]);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.