I can not clean list of li elements that is generated dynamically

1

I have a dynamic list generation, so I'm adding li through input text .

I have a button to clear all the entries of li and this is his code:

function removeTudo() {
    listaCompleta = document.querySelector("#listaCompleta");
    var lis = document.getElementById("listaCompleta").getElementsByTagName("li");
    for (var i = 0; i < lis.length; i++) {
        listaCompleta.removeChild(lis[i]);        
    }
  }    
    clearBtn.addEventListener("click", function () {
    removeTudo();
})

I would like to know the following. when I declare the variable "lis" my idea is to update it with the new entries I've been putting.

When I send a console.log into the function I know that it is catching everything right. However, when removing all entries, the code removes 1 element yes and another element does not. So if there are 8 items, it removes 4 interspersed. Why does this occur?

    
asked by anonymous 15.12.2016 / 23:09

2 answers

0

Without knowing how HTML is, it is difficult to help. But you can change the code for:

function removeTudo() {
    var lis = document.querySelectorAll("#listaCompleta li");
    for (var i = 0; i < lis.length; i++) {
        var li = lis[i];
        li.parentElement.removeChild(li);
    }
}
var clearBtn = document.querySelector('button');
clearBtn.addEventListener("click", removeTudo);

So by using the "#listaCompleta li" selector you get all li within #listaCompleta and with li.parentElement.removeChild(li); you no longer need a pointer to #listaCompleta to remove elements.

jsFiddle: link

    
15.12.2016 / 23:15
0

If you are referring to the code

16.12.2016 / 00:54