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:
Then choose â€˜CSS Selectorâ€™ for the â€˜Selection Methodâ€™:
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:
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.
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.