0

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614

2 Answers2

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>
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

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>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80