skip to Main Content

how do I extract the content from this HTML elements:

<span class="woocommerce-Price-amount amount">399&nbsp;<span class="woocommerce-Price-currencySymbol">USD</span>
</span>

I would like to get the price (which here is 399).

var number_price = document.querySelector(".woocommerce-Price-amount");

I gets the hole elements include parent and child HTML elements. I would like to get only the number 399 here.

2

Answers


  1. Read the text and parse it as a number. It will be fine as long as the number is the start of the string.

    var number_price = parseFloat(document.querySelector(".woocommerce-Price-amount").textContent);
    console.log(number_price)
    <span class="woocommerce-Price-amount amount">399&nbsp;<span class="woocommerce-Price-currencySymbol">USD</span>
    </span>
    Login or Signup to reply.
  2. You can get the text from the firstChild, which is a text node.

    const number_price = document.querySelector(".woocommerce-Price-amount");
    console.log(number_price.firstChild.textContent.trim());
    <span class="woocommerce-Price-amount amount">399&nbsp;<span class="woocommerce-Price-currencySymbol">USD</span>
    </span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search