1

How to divide the price by 2 using JS? I tried this but it didn't work.

<script>
const a = parseInt(document.getElementById('price_value').textContent)
const b = 2
const result = a / b

document.getElementById('result').innerHTML = result
</script>

<body>
<span class="wcpa_price"><span class="woocommerce-Price-currencySymbol">$</span><span class="price_value">29.00</span></span>
<div id="result"></div>
</body>

2 Answers2

0

2 things:

  • the script tag must be below the elements. Otherwise, when the script ran, the elements would not have been loaded yet.

  • There is no element with the id price_value. You should be selecting the element with that class instead.

<body>
<span class="wcpa_price"><span class="woocommerce-Price-currencySymbol">$</span><span class="price_value">29.00</span></span>
<div id="result"></div>
<script>
const a = parseInt(document.querySelector('.price_value').textContent)
const b = 2
const result = a / b

document.getElementById('result').innerHTML = result
</script>
</body>
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Problem here is that you do not have element with id price value but you have class on it called like that.

Issue is here:

document.getElementById('price_value')

To fix this add id "price_value" on the span element of the price.