• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

121
Views
How Can I Replace List Items Instead of Adding on To Them

I am new to JavaScript and I am creating a simple game. The code below is used to print the score. However, instead of updating the values it adds them below the existing one so the output looks like this:

Player 1 = 0 Player 2 = 0 Player 3 = 2 Player 4 = 0 Player 5 = 0 Player 1 = 0 Player 2 = 2 Player 3 = 2 Player 4 = 0 Player 5 = 0

How can I update the score value instead of just reprinting the list items? I have tried using replaceChild but it has not worked for me but I could be using it wrong. I have also tried a Boolean to only run the playerScore created in line 4 of the code once, but I cannot seem to pass it out of the if loop. Anything will help!

   function printScore(){
              var i=0;
              while(names[i] != null){
               const playerScore = document.createElement('li');
               playerScore.id = i +'artist';
               playerScore.innerText=names[i] + " = " + window['player' + i];
               currentScores.appendChild(playerScore);
               i++;
            }
        }
almost 3 years ago · Santiago Gelvez
1 answers
Answer question

0

A quick and easy solution is just use innerHTML to empty the destination before you start adding.

   function printScore(){
          currentScores.innerHTML = "";              
          var i=0;
          while(names[i] != undefined){
           const playerScore = document.createElement('li');
           playerScore.id = i +'artist';
           playerScore.innerText=names[i] + " = " + window['player' + i];
           currentScores.appendChild(playerScore);
           i++;
        }
    }
almost 3 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error