A.Copland
A.Copland

Reputation: 57

Javascript updating textContent

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.

Upvotes: 0

Views: 379

Answers (1)

user24950814234
user24950814234

Reputation: 2037

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);
}

Upvotes: 1

Related Questions