Updating an element with Javascript

Asked

Viewed 1,878 times

-1

I have this code:

let inicial = -0;
const numeros = [1,2,3,4,5,6,7,8,9,10];

function proximo (){ 
       inicial++
       document.getElementById("lugar").innerHTML=''

       alert(inicial)
    
    for(let i = inicial-1; i < inicial+2; i++){
        const ul           = document.createElement('UL');
        const numerosUl    = document.createTextNode(numeros[i]);
        const lugarElement = document.getElementById("lugar");
      
        ul.appendChild(numerosUl);
      
        lugarElement.appendChild(ul);
    }
}


function limpar(){
  document.getElementById("lugar").innerHTML=''
}
<html>
  <button onClick="proximo()"> Próximo </button>
  <div id="lugar">  Teste </div>
  
  
  <button onClick="limpar()"> Limpar </html>
</html>

It is appearing in 3 in 3 numbers, however, I want, every click it updates itself with the own numbers of the sequence array.

Example: If you click now, it will appear 1,2,3. I want that when you click the next time, appear: 4,5,6 and the next: 7,8,9 and at the last click, appear: 10. Not creating new elements in the body but updating it.

Could someone help me and if possible explain what was done? I just want this change, starting from the number that does not appear on the screen, that at first it is, 1 to 3, and starting from the 4 and go to 6 and start from the 7 and go to the 9 and when last click appear the 10.

  • 3

    What is the difference between this doubt and your doubt previous question? The answer there did not solve the problem?

  • @bfavaretto no, it 'ate' the number 7. N know why.

  • 1

    Okay, I get it. But you could have commented on that in @dvd’s own reply to the other question, I’m sure it would review the code. When you mark the answer as accepted (green tick), as you did there, it looks like the problem is solved.

  • Yes, I hadn’t even noticed it was my friend who saw it, but it helped me with that code, I understood some things

  • Another thing to watch out for, that only one of the answers below corrects: you are generating invalid HTML, you cannot insert a direct Node text into UL. You need a LI around the Node text, and the LI yes goes inside the UL.

4 answers

2


Use a for simple and within the for utilize if (!numeros[inicial]) break;. This way the repetition will be stopped if you do not find a valid value.

let inicial = 0;
const numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const lugarElement = document.querySelector("#lugar ul");

function proximo() {

  /* Limpa a tela caso ainda possua números a serem exibidos */
  if (inicial < numeros.length)
    lugarElement.innerHTML = "";

  for (let i = 0; i < 3; i++) {
    if (!numeros[inicial]) break;

    /* Adiciona o LI dentro do UL */
    lugarElement.insertAdjacentHTML("beforeEnd", `<li>${numeros[inicial]}</li>`);

    inicial++;
  }
}
<button onClick="proximo()"> Próximo </button>
<div id="lugar"><ul></ul></div>

1

    let inicial = 0; 
const numeros = [1,2,3,4,5,6,7,8,9,10];

function proximo (){ for(let i = 0; i <= 3; i++){ 

    if(numeros[inicial] != null){

        const ul           = document.createElement('UL');
        const numerosUl    = document.createTextNode(numeros[inicial]);
        const lugarElement = document.getElementById("lugar");
        inicial++;

        ul.appendChild(numerosUl);

        lugarElement.appendChild(ul);
    }
}
  • I think it’s good to warn that you can’t hang an Node text directly on an UL.

1

For a simple code like that, I wouldn’t even use the for:

var inicial = 0;
var numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var lugar = document.getElementById('lugar');

var ul = lugar.appendChild(document.createElement('ul'));
var li1 = ul.appendChild(document.createElement('li'));
var li2 = ul.appendChild(document.createElement('li'));
var li3 = ul.appendChild(document.createElement('li'));

function proximo() {
  if ((inicial + 1) > numeros.length)
    // se já acabaram os números do array, saia da função
    return;
   
   // se já acabaram os índices do array, o valor é esvaziado
   li1.textContent = numeros[inicial++] || "";
   li2.textContent = numeros[inicial++] || "";
   li3.textContent = numeros[inicial++] || "";
}
ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
<html>
  <button onClick="proximo()"> Próximo </button>
  <div id="lugar"> </div>
</html>

But if in your case you have more than 3 items, it is impossible to create all <li>s individually. If you need to use for, the above answers are sufficient, but with an addendum:

Never update the DOM within one for

That’s a bad practice for performance (the article talks about jQuery, but the tip is general).

So, if you’re going to use a loop, change it to HTML, with all the items together:

...
function proximo() {
    ...
    var html = '';
    for(...) {
        html += '<li>' + (numeros[inicial++] || "") + '</li>';
    }
    ul.innerHTML = html;
...
}
  • Your tip is good. But I believe that if the last appendchild (which actually inserts things on the page) was after the for, there would be no problems.

  • The problem is that your code is restricted. What if instead of 10 numbers were 100?

  • @bfavaretto there would be problems because, unlike jQuery, Node.appendChild does not accept an array of elements. @dvd yes, so I made it clear that if there are more than three items (or variable amount), use the for even, but with that correction.

  • 1

    I meant that assembling any list in for has no problem as long as UL has no father. Only UL appendchild in div that will cause a reflow.

  • Aaah, really!

1

You can do this way by adding the elements at once without using createElement.

Note that the code below will insert only 1 <ul> with due diligence <li>, which is correct, not several <ul> as your code suggests.

let inicial = 0;
const numeros = [1,2,3,4,5,6,7,8,9,10];

function proximo (){ 

   if(inicial >= numeros.length) return; // sai da função caso "iniciar" seja maior ou igual ao número de itens na array

   document.getElementById("lugar").innerHTML=''; // esvazia a div

   var els = '';
   for(let i = inicial; i <= inicial+2; i++){
      if(numeros[i]){ // somente se houver algum valor   
         els += '<li>'+numeros[i]+'</li>'; // concateno os novos elementos
      }
   }

   document.getElementById("lugar").innerHTML = "<ul>"+els+"</ul>";
   inicial += 3; // aumento o valor em +3
}

function limpar(){
    document.getElementById("lugar").innerHTML=''; // esvazia a div
}
<button onClick="proximo()"> Próximo </button>
<div id="lugar"></div>
<button onClick="limpar()"> Limpar </button>

  • This list already has another structure, right? UL for each item?

  • Really... although the code of the question suggests it... I’ll arrange

Browser other questions tagged

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