JavaScript variables in Google Tag Manager: How to extract almost any visible information from your website

I recommend basing tag configuration on Data Layer variables (strangely enough to start this article form that, I know it). But on the other hand, there could be lots of situations when we can’t afford data layer configuration for different reasons. That’s when JavaScript variables in GTM come to the rescue. Below I’m gonna describe how to pull almost any visible information from a website into Google Tag Manager variable.

As an example, consider the case when we need to extract transaction ID on the purchase confirmation page.

How to find the exact path for a specific part of the information

Firstly, we need to find an element and its path on the website. For that we open Developer Tool in a web browser (I use Google Chrome). Then we toggle Inspect Element Mode on. In Chrome for Windows, we can use a shortcut Control+Shift+C. In this mode click on a proper element and the panel will show it in code.

In the code, we choose the element and click the right mouse button on it. Then copy JS path. Further manipulation will be in the console.

As a result, we got the element’s path. Paste it into the console and see the result.

But we need not the whole element, but only a piece inside it with ID. So then we use innerText property to return the text content on the element.

To separate ID from other text we can use the split function. The function looks the following: f(splitter, limit). In this case, we will use space as a splitter and no limit. In return, we’ll have access to all split elements.

The fifth element is ours. So we add the number of element in brackets and got the exact path to the ID.

Custom JavaScript variable configuration in GTM

Obtained path we can use for custom JavaScript variable. For that purpose we click Variables > New in the GTM panel and choose Custom JavaScript. The JS code looks the following:

function() {
    var id = document.querySelector("#content > div > div > div > div.nv-content-wrap.entry-content > p.has-text-align-center.has-medium-font-size").innerText.split(" ")[4];
    return id;
  }

So then we copy the code in GTM and save the variable.

After all, we can check it in the Google Tag Manager debugger and use the variable for different tags (e.g. Google Ads or Google Analytics).

In the same way, you can pull any information from your website as a JavaScript variable. If you have some problems with it or additional questions – write it in comments.