Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
how to prevent innerHTML repeating the previous value

I'm a JS learner and want to create an app that will calculate the average from input values. So far I've managed to push the entered input values into an array. However, when I want to display them, the previous value is repeated. So I'm near the end. But now I'm stuck. Can you lend me hand with that?

        Enter
      </button>
      <p id="numbersEntered"></p>
      <button id="avg" type="button">Average</button>
      <p id="average"></p>
  
   let numbersEntered = document.querySelector("#numbersEntered");
   let inputEl = document.querySelector("#input");

   // buttons
   let enter = document.querySelector("#enter");

   let numArr = [];

   enter.addEventListener("click", displayNums);

   function displayNums() {
   let newNumber = inputEl.value;
   numArr.push(newNumber);
   console.log(numArr);

   for (let i = 0; i < numArr.length; i++) {
    numbersEntered.innerHTML += numArr[i] + ",";
  }
  }

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Instead of appending numArr to innerHTML, simply overwrite it instead. Also, since you're only writing plain text, it is recommended to use textContent instead of innerHTML:

function displayNums() {
    let newNumber = inputEl.value;
    numArr.push(newNumber);
    console.log(numArr);

    numbersEntered.textContent = numArr.join(', ');
}

There is no need to use a for loop when you can use Array.prototype.join to print the array out.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can just clear the innerHTML before appending;

function displayNums() {
   let newNumber = inputEl.value;
   numArr.push(newNumber);
   numbersEntered.innerHTML = "";  //Clear the innerHTML
   for (let i = 0; i < numArr.length; i++) {
     numbersEntered.innerHTML += numArr[i] + ",";
   }
}

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda