Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

62
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++;
            }
        }
7 months 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++;
        }
    }
7 months ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos