How to update an element with JavaScript [duplicate]

-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's showing up in 3 in 3 numbers, however, I want it to update itself every time it clicks on the array itself.

Example: If you click now, 1,2,3 will appear. I want it when I click next time, it appears: 4,5,6 and in the next: 7,8,9 and in the last click, it appears: 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, to start from the number that does not appear on the screen, that is from the beginning, 1 to 3, and start from 4 and go to 6 and start from 7 and go to 9 and when you last click 10.

    
asked by anonymous 20.02.2018 / 19:33

4 answers

2

Use for simple and within for use if (!numeros[inicial]) break; . This will stop the retry if it does 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>
    
20.02.2018 / 19:53
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);
    }
}
    
20.02.2018 / 19:51
1

For a simple code like this, I would not even use 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 not possible to create all% s of% s individually. If you need to use <li> , the answers above are sufficient, but with an addendum:

Never update the DOM within a for

This is a bad practice for performance (the article talks about jQuery, but the hint is general).

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

...
function proximo() {
    ...
    var html = '';
    for(...) {
        html += '<li>' + (numeros[inicial++] || "") + '</li>';
    }
    ul.innerHTML = html;
...
}
    
20.02.2018 / 20:32
1

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

  

Note that the code below will insert only 1 <ul> with its due    <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>
    
20.02.2018 / 21:10