0

I am having an issue with updating text content, if I select the element with document.querySelector() then it works but if I store the element in an object then I can't seem to update it.

Example:

let player1 = {
    totalScore: 0,
    currentScore: 0,
    totalScoreBox: document.querySelector('#score--0').textContent,
    currentScoreBox: document.querySelector('#current--0').textContent
}

const updatePlayerScore = (player, value) => {
    player.totalScore += value;
    player.currentScore += value;
    player.currentScoreBox = parseFloat(player.currentScore); //Doesn't work
    document.querySelector('#current--0').textContent = parseFloat(player.currentScore); //Works
}

https://jsfiddle.net/Copopops/rsuc7m4g/1/

Thanks in advance.

A.Copland
  • 17
  • 5
  • 1
    Duplicate of [Setting innerHTML: Why won't it update the DOM?](https://stackoverflow.com/q/8196240/4642212); the same applies to `textContent`. – Sebastian Simon Mar 21 '21 at 21:31

1 Answers1

1

This line currentScoreBox: document.querySelector('#current--0').textContent retrieves the textContent as a string, and stores that string in the currentScoreBox variable. When you set currentScoreBox to another string, all you are doing at that point is replacing the value of that variable, it is in no way attached to your DOM.

Instead, store the node itself.

let player1 = {
    totalScore: 0,
    currentScore: 0,
    totalScoreBox: document.querySelector('#score--0'),
    currentScoreBox: document.querySelector('#current--0')
}

const updatePlayerScore = (player, value) => {
    player.totalScore += value;
    player.currentScore += value;
    player.currentScoreBox.textContent = parseFloat(player.currentScore);
}
user2867288
  • 1,979
  • 16
  • 20