Using CSS Selector Variables in Google Tag Manager

Using CSS Selector Variables in Google Tag Manager

Alex YastrebenetskyUncategorizedLeave a Comment

Google Tag Manager has been releasing a slew of new features lately, the most noticeable being the new Version 2 user interface.  But, under the hood GTM has also received a lot of additional features, including the ability to use CSS selectors in triggers (as expertly described by Simo Ahava).  However, CSS Selectors have also been added to the additional variable types as well.

Why Would I Use This?

The benefit of Google Tag Manager is that it allows marketers, developers, SEOs, and optimizers the ability to create, edit and remove tags in a simple online interface.  Using the CSS Selector Variable allows you to use non-standard element attributes as well as data attributes from an element that may not be the element Google Tag Manager references in its interaction.

How Does it Work?

Setting up the CSS Selector Variable is easy.  First, create a new DOM Element Variable in your Google Tag Manager container:

Using CSS Selector Variables in Google Tag Manager 1

Then choose ‘CSS Selector’ for the ‘Selection Method’:

Using CSS Selector Variables in Google Tag Manager 2

Then comes the real magic. For the ‘Element Selector’ input, you will need to enter the CSS Selector that you want to get data from.  Here you can use standard CSS Selector syntax to find the element you are looking for (Check out the CSS Diner game to brush up on CSS Selector syntax).  The cool thing about the CSS Selector variable is that you use the selector to pinpoint an element and then you use the attribute name to return the value from any attribute of the element you have found.  

For example, let’s say you had an anchor tag like so:

<a href=â€#†id=â€main†class=â€navlink navbar†data-target=â€homeâ€>Link Text</a>

The CSS Selector variable allows you to find this element in one of many ways, like this:

Using CSS Selector Variables in Google Tag Manager 3

The key thing to remember is that the variable is going to select the first element in the DOM with an ID of ‘main’ and return the value of the ‘data-target’ attribute.  So in many cases you need to be more specific.  One way to do this is to add conditions to a standard selector.

Using CSS Selector Variables in Google Tag Manager 4


Here we look for an <a> tag that has a data-target=â€homeâ€.  The variable finds the first match in the DOM and, since we have not selected an attribute, it returns the text between the <a> and </a> tags.  In this case the variable would return “Link Text†using our example above.

For a full description of the selectors you can use for this application, check out the W3 Schools section on CSS Selectors.  


Learn more about our analytics services