0

I am getting some numbers from the DOM, one originalPrice and one discountPrice. Now i wanna write out the % differens between the two. These numbers can alway vary. So my question:

Can i calculate variables? For exaple:

((originalPrice - discountPrice) / originalPrice) * 100; and then use Math.round to get rid of decimals? When i try it i only get NaN

This is what i have tried:

      var originalPrice = document.querySelector('.original-price')
      var discountPrice = document.querySelector('.from-price')

Math.round((originalPrice - discountPrice) / originalPrice) * 100;

I only get NaN. I expect differens in %

Mikhail Zhuikov
  • 1,213
  • 2
  • 9
  • 19
C. Doe
  • 19
  • 3

2 Answers2

0

If you look at MDN you will see that you are getting back a reference to the HTMLelement, in each case, which is different from its value.

It's not clear from your example what the HTML element is, but you need to either grab its TEXT or its VALUE

MikeB
  • 580
  • 3
  • 18
0

The things you are storing in variables, are not the values, they are <div>s themselves (instances of HTMLDivElement object). And as these objects cannot be parsed as numbers, the attempt to calculate them leads to NaN.

To get these values and to be able to make calculations, you need to:

  1. Get the text content from these div's and
  2. Parse them to Number type (by default, all text content is of type String).

So your variables could look like this (as Prasanth Ganesan mentioned):

var originalPrice = parseInt(document.querySelector('.original-price').innerText);
// or
var discountPrice = Number(document.querySelector('.from-price').innerText)

If the content of these divs is guaranteed to be digits (not text) you will store proper Number values into your variables and for sure will be able to make calculations.

Alex Naidovich
  • 188
  • 4
  • 15
  • parseFloat is a much better option for parsing strings with numeric data when you are expecting those numbers to be in base 10. parseInt can behave unexpectedly and interpret things in different bases if, say, you have leading zeroes or some other characters in your string. https://stackoverflow.com/questions/12812863/difference-between-parseint-and-parsefloat – J. Stott Jun 10 '19 at 13:30
  • @J.Stott I think the question itself is not about this. The OP wants to get values from `div`s to not to calculate `div`s themselves. And the formula he gave starts with `Math.round()` so I don;t think he cares much about decimals. P.s. As for me it in general looks like "left-hand rendering"... The data should be turned into markup, not vice versa... – Alex Naidovich Jun 10 '19 at 14:59