Search code examples
javascriptcssgoogle-tag-manager

CSS Selector For Product Price On Page


In Google Tag Manager, I'm attempting to store the customers cart subtotal as a variable. I'm having difficulties with accessing the element on the page via css selectors. My desired output would be to store the below subtotal "$254.97" as a float variable --> 254.97

GTM JavaScript Variable:

function() {
  var priceText = document.querySelector('ENTER_CSS_SELECTOR_HERE');
  var regex = /([0-9.,]+)/;
  if (regex.test(priceText.innerText)) {
    return priceText.innerText.match(regex)[0].replace(/,/g, '');
  }
}

The elements on the page are organized as such:

<div class="grid__item one-half">
                    <p class="cart__subtotal h4"><span class="Bold-theme-hook-DO-NOT-DELETE bold_cart_total" style="display:none !important;"></span><span>$254.97</span></p>
                  </div>

Solution

  • document.querySelector('.cart__subtotal span:nth-child(2)');