Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can i use textContent in JS for adding to element numbers?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading