skip to Main Content

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

Answers


  1. 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>
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search