0
I’m making a small javascript program to generate a tabulation. To prevent duplicates from occurring, I put in a small code snippet to clear the list before generating the table
let numero = window.document.getElementById('numero');
if (numero.value.length != 0) {
let tabuada = window.document.getElementById('lista');
let itens = window.document.getElementsByTagName('li');
for (let i = 0; i <= 10; i++) {
tabuada.removeChild(itens[i]);
}
However, the list is not generated if I keep this code. Here is the full code:
let numero = window.document.getElementById('numero');
if (numero.value.length != 0) {
let tabuada = window.document.getElementById('lista');
let itens = window.document.getElementsByTagName('li');
for (let i = 0; i <= 10; i++) {
tabuada.removeChild(itens[i]);
}
let novo = window.document.createElement("li");
tabuada.appendChild(novo);
let section = window.document.getElementById('section');
section.style.height = "auto";
for (let i = 0; i <= 10; i++) {
let novo = window.document.createElement("li");
let txtnovo = window.document.createTextNode(`${Number(numero.value)}x${i} = ${Number(numero.value) * i}`);
novo.appendChild(txtnovo);
tabuada.appendChild(novo);
}
}
It worked. But the following code snippet: while(timed.children.length > 0) { timed.removeChild(timed.Children[0]); } I didn’t get it right. Why does the removal always happen in the first position of the children of "tabuada"? Java script automatically reallocates the rest?
– Matheus10772
@Matheus10772 This excerpt you quoted is to remove the
<li>
within the<ul>
. Imagine that the<ul>
has 3<li>
, soon hischildren.length
shall be equal to 3. When removingchildren[0]
thelength
will be equal to 2. Then we remove again thechildren[0]
and thelength
will become 1 and so on until there is no more<li>
within the<ul>
. It works like a stack of paper, you will always remove the first paper from the stack until there is no more.– Marcelo Vismari
Thank you !!! D
– Matheus10772