0

I have this script that is design to get the values in the targeted p tags which consist of numbers which I end up using as a addition situation the problem is the

answer is suppose to be 3 not 12 the script is treating the plus symbol as a concatenation situation so how can I make the script do addition in that situation with the the variable one and two?

Here is my code

var one= document.querySelector('#oneEx').innerHTML;
var two= document.querySelector('#twoEx').innerHTML;

var total= one+two;

document.write(total);
.mathDesign{
  display: inline-block;
}
<p id='oneEx' class='mathDesign'>1</p>
<p class='mathDesign'>+</p>
<p id='twoEx' class='mathDesign'>2</p>
<p class='mathDesign'>=</p>
  • 1
    1 and 2 are string. One option us using `Number()` to convert string to number – Eddie Jun 25 '18 at 06:49
  • 1
    add `+` as prefix at `document.querySelector` – Jack jdeoel Jun 25 '18 at 06:50
  • 1
    Possible duplicate of [How to force JS to do math instead of putting two strings together](https://stackoverflow.com/questions/4841373/how-to-force-js-to-do-math-instead-of-putting-two-strings-together) – Sebastian Simon Jun 25 '18 at 06:58

2 Answers2

1

@fsofb, when you get innerHTML then var type is HTML content. so basically your "+" here join two string value not the integer. so convert that string to integer and try.

Convert your

 var total= one+two;

With

 var total= parseInt(one)+parseInt(two);

and it works!!

Priyal Pithadiya
  • 889
  • 1
  • 5
  • 12
0

You need to convert it into number before adding. innerHTML always returns a string. so in order to add them, first convert to number. parseInt() for integer and parseFloat() for floating point, or just Number()

var one= document.querySelector('#oneEx').innerHTML;
var two= document.querySelector('#twoEx').innerHTML;

var total= Number(one) + Number(two);

document.write(total);
.mathDesign{
  display: inline-block;
}
<p id='oneEx' class='mathDesign'>1</p>
<p class='mathDesign'>+</p>
<p id='twoEx' class='mathDesign'>2</p>
<p class='mathDesign'>=</p>
Akhil Aravind
  • 5,741
  • 16
  • 35
  • OMG thank you so much I like this method Akhil Aravind thanks for your advice. –  Jun 25 '18 at 07:08