Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!