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]);
}
}
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.
– Daniel Mendes
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);
}

– Gabriel Caetano
Solved with the answer below, vlw
– Gabriel Caetano