In Google Tag Manager, you can create variables using JavaScript to grab an element from an app or page.
In this tutorial, I’ll show how to execute a JavaScript as a user defined variable in GTM grabbing a value from an HTML element.
Executing a javascript variable in GTM starts with a user defined variable. A requirement of entered JavaScript is it must end in a return value, otherwise it won’t validate.
This script targets an HTML element class.
Returns defined_variable function () { var defined_variable = document.getElementsByClassName('field_defined_variable’)[0].innerHTML; return defined_variable; }
Adding the JavaScript Value as a Dimension
Once the script is added, you can call the script from a tag fire, by adding the user defined variable reference in the tag. Adding this reference will execute the JavaScript when the tag fires, and the returning value can be passed as a custom dimension.
The value returned in the script will be a custom dimension in Google Analytics. Creating a custom reports allows identifying the primary dimension as the returned value from the JavaScript executed in Google Tag Manager.