• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

120
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda