In Google Tag Manager it is possible to trigger triggers based on css selector matching. If a html element matches the css selector, a trigger gets triggered (more details available here: http://www.simoahava.com/analytics/matches-css-selector-operator-in-gtm-triggers/)
Currently I use the following css selector matching to identify if a trigger should be triggered or not:
div#admin-button-id, div#admin-button-id *
So the first part before the comma indicates one possibility, it matches all div elements with the id admin-button-id.
The second possibilty (after the comma) matches all html elements that are children of a div element with id admin-button-id. This works, but I would prefer a version in which I would not have to duplicate div#admin-button-id. So, something like
div#admin-button-id *?
to indicate that the children are optional. Is there such a valid construct?
Based on suggestions from @nyen I came up with the following solution:
I have to deal with the following markup code (unnecessary css classes ommited):
<div id="admin-button-id">
<span>
<span>Administration</span>
</span>
</div>
It is possible to click on various parts of this button, either the innermost span, the intermediate span or the outer div. But only the outer div includes an id which I can use to match against in my GTM trigger. So within GTM I created a user-defined variable called 'calculatedClickId' of type 'Custom JavaScript'. The custom function searches for the id in the dom tree in the outward direction (from the innermost span to the outher div):
function() {
if ({{Click Element}}.id != "") {
return {{Click Element}}.id;
}
if ({{Click Element}}.parentNode.id != "") {
return {{Click Element}}.parentNode.id;
}
return {{Click Element}}.parentNode.parentNode.id;
}
The {{Click Element}}
is the html element that is provided by GTM. So now it doesn't matter where within my html element a click occurs, the variable calculatedClickId
is always set to the id of the outer div.
This allows me to use the variable calculatedClickId
within my trigger configuration easily:
I'm aware that the custom javascript method is not bulletproof (yet) and might be refined further, but this solution is an improvement over the css selector method.