If there’s a piece of text loaded on a page that you would like to collect as part of your data analysis, there are several ways to do this using Google Tag Manager.
In today’s example, we’re going to walk through how to collect the header text on one our blog posts – but first, you might ask why we’d want to do this?
Well, maybe we want to see which blog topics generate the most engagement. We could do this by tracking submitted contact forms or clicks to get in contact at the bottom of our blog posts as Google Analytics Events – and we could send the title of the blog through to Google Analytics as the Event Label. This will then allow us to easily breakdown and report on blog post engagement by topic.
How To Collect Header Text as a Variable in GTM
This process will work for any piece of text that’s loaded on a webpage – but we’ll look at the Header in this instance, as an example. The first thing to do is check the code behind the text that you want to collect. The easiest way to do this is to right-click on the piece of text, then ‘Inspect’ (on Chrome).
By doing this, we can see that this particular blog header is the ‘h1’ element on our page. Now that we know this, we can create a DOM Element Variable in Google Tag Manager to pick up this text.
Using a DOM Element Variable in GTM to Collect H1 text
If you want to gather any static piece of text that is loaded on a page via Google Tag Manager, you will want to use a DOM Element Variable.
DOM = Document Object Model, which is a rather fancy way of referring to all of the stuff that loads on the page.
To specifically collect the ‘h1’ element text, we need to create a variable as per below:-
You can then test if your variable picks up the text you’d expected by using GTM’s debug mode. You may find that the value is undefined until the ‘DOM Ready’ event because it is only once the ‘DOM Ready’ event occurs that we know the content of the page has fully loaded in.
Once you can see the text you’d expected, you can then use this new variable in any tags when tracking Google Analytics Events that occur on this page post-DOM Ready.
Important note: the DOM Element Variable will always return the first match it finds on the page, so if you have multiple ‘h1’ elements on the page, it will only return the text from the first element.
You can use the same technique described above to pull in any static text loaded on a page – you just need to use the correct Element ID or CSS Selector for the element you want to target. You can find out more about testing your CSS Selectors in Chrome here.
Any questions on the above? Let us know in the comments below!
7 responses to “How To Pull in Header Text as a Variable Using Google Tag Manager”