Search code examples
javascriptcss-selectorsgoogle-tag-manager

Extracting Price as a Variable Using Google Tag Manager from Specific Page Element


I'm aiming to retrieve the price value ($278.45) from a designated HTML element using Google Tag Manager and store it as a variable for further use.

Target Element:

<div class="sc-fbgIAx CmZAI pricing-summary-row">
    <span class="sc-dxUwTY BLzzV">Total Due Now (USD):</span>
    <span data-testid="total-due" class="sc-dxUwTY BLzzV">$278.45</span>
</div>

I've made an attempt using JavaScript within GTM:

var totalDueElement = document.querySelector('[data-testid="total-due"]').textContent;

However, I haven't been successful in retrieving the value. Could someone please provide a solution and explain the correct approach? I'm seeking guidance on how to capture similar values effectively.


Solution

  • In "Custom Javascript" variable you should use function that'll return your variable.

    In your case:

    function returnRevenue () {
        return document.querySelector('[data-testid="total-due"]').textContent;
    }
    

    It will return '$278.45' in your case.