Home > Software design >  CSS Selector For Product Price On Page
CSS Selector For Product Price On Page

Time:10-08

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 >
                    <p ><span  style="display:none !important;"></span><span>$254.97</span></p>
                  </div>

CodePudding user response:

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

CodePudding user response:

you can use a normal class selector like this

document.getElementsByClassName("grid__item")

CodePudding user response:

There are several ways to solve this problem. Here are some of them: First, name your function.

function myFunction() {
    var priceText = document.querySelector('.cart__subtotal span:last-child');
    var regex = /([0-9.,] )/;
    if (regex.test(priceText.innerText)) {
      return priceText.innerText.match(regex)[0].replace(/,/g, '');
    }
}

or

function myFunction() {
    var priceText = document.querySelector('.Bold-theme-hook-DO-NOT-DELETE.bold_cart_total   span');
    var regex = /([0-9.,] )/;
    if (regex.test(priceText.innerText)) {
      return priceText.innerText.match(regex)[0].replace(/,/g, '');
    }
}

and console.log(myFunction());will display this in the console 254.97

  • Related