Home > Back-end >  Can i use textContent in JS for adding to element numbers?
Can i use textContent in JS for adding to element numbers?

Time:01-31

I'm trying to make program that every time i click a button a numbers is being added to to a html element. I'm trying to do it using textContent like the code below, but every time the element "gets" the number, instead of doing the calculation and show the sum, its just adding the number as Like, instead doing that:

score: 2 4 >> score:6

score: 6 1 >> score:7

its doing that: score:241

this is the code:

HTML:

  <div id="player1score">
                <h2>score: <span id="sumscore1">0</span></h2>
                <p id="player1dice">-</p>
            </div>

JS:

function render() {
let randomNumber = random()
sumscore1.textContent =  randomNumber
}

Maybe textContent cant gets numbers and attribute the numbers as string?

CodePudding user response:

textContent returns a string (or null, in some cases). Using the addition assignment operator = results in a concatenation operation if one of the operands is a string.

You need to cast it to an integer or other Number first to perform arithmetic operations on it:

function render() {
    let randomNumber = random()
    sumscore1.textContent = parseInt(sumscore1.textContent || 0)   randomNumber
}
  •  Tags:  
  • Related