3

Somebody please help me. I'm not sure what I'm doing wrong here:

I'm trying to add up some numbers.

Instead the adding the 2 numbers it is just placing the 2 numbers next to each other; as in: 3 + 3 = 33 (instead of 6) !!!

If I replace the + with a * then it returns the correct result (9)

What is happening?

<p id="A">3</p> 
<p id="B">3</p>

<p id="score"></p>

<script>

var AA = document.getElementById("A").innerHTML;
var BB = document.getElementById("B").innerHTML;

var result = AA + BB;

document.getElementById("score").innerHTML = result;

</script>
leo weston
  • 47
  • 5

2 Answers2

4

That's because they're strings so you're getting string concatenation. Convert them to numbers before performing addition.

AA = parseInt(AA, 10);
BB = parseInt(BB, 10);
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
1

What you are getting back from the html are strings, not numbers. You need to parse them as numbers first:

var AA = parseInt(document.getElementById("A").innerHTML, 10);
var BB = parseInt(document.getElementById("B").innerHTML, 10);

parseInt will convert the string to a number, and make your addition work correctly. The second parameter in the parseInt call is the radix, which will help prevent confusing mishaps when it comes to actually parsing the numbers

millerbr
  • 2,951
  • 1
  • 14
  • 25