Home > database >  How to get an element from html after changing
How to get an element from html after changing

Time:01-05

//HTML code part

<section >
  <p >
    Player's Score:
    <span id="pScore"> 0 </span>
  </p>
</section>

//JS code part

const min = 1;
const max = 10;
let playerPoints = 0;
let computerPoints = 0;

const choices = section.addEventListener('click', function (event){ 
const x = Math.trunc(Math.random() * (max - min))   min;
const x = Math.trunc(Math.random() * (max - min))   min;
    if (event.target.id === 'rock' && x > 6) {
       console.log('Player WIN!!');
       playerPoints  ;
       document.getElementById('pScore').textContent = playerPoints;

//UPDATE In this code you can see this part '&& x > 6'. I made the computer this way to make a choice between rock paper scissors. Try to show you a short code part as you asked me, I hope it's enought. And thanks for show the problem of screenshots don't make the same mistake again

So I want to make a game, if you collect 3 points you win it. It is almost done I just want to get the players current points what always changeing.This is my html code what contains the value or property, it can be the problem I don't what is it for sure.You can see the changeing when player or computer collect point

I used document.getElementById('').textContent = variable to change the value, but after changeing can't get it again.

Tried to get back it with the same way but doesn't work. As you see in the image If print it I can see the current number But if try again with the id selector or span selector or even class selector it shows nothing.

CodePudding user response:

I think you'll be best using a variable to store the score instead of using an DOM element. Then you can create a function to update it, and every time you need to change the score, use the function instead of setting it directly.

Something like this:

let points = 0;
let playerScoreDisplay = document.getElementById('pScore');

function updatePoints(value){
    points = value;
    playerScoreDisplay.textContent = points;
}
  • Related