aphextwig
aphextwig

Reputation: 553

Parent Class in Google Tag Manager

I found this Google Tag Manager macro script (http://viget.com/advance/gtm#elementclass) to identify if an element's parent has a specific class value.

function crawlByClassName () {
var el = {{element}};

while (el && el !== document.body && el.className !== 'INSERT CLASS NAME') {
    el = el.parentElement;
}

return el.className === 'INSERT CLASS NAME';
}

Is there a way to modify it to record the value and then use a rule to specify the name? Or is there a different way to achieve this?

Upvotes: 1

Views: 7162

Answers (2)

aphextwig
aphextwig

Reputation: 553

Thanks @kevintechie. Your method might work.

I was able to find another way here https://plus.google.com/100582165749296472339/posts/fa6iKeuF6ig

I can use this as the macro:

function() {
return {{element}}.parentElement.className;
}

Then specify the class name in the rule. This means there's only one macro and not one for every class.

Upvotes: 1

kevintechie
kevintechie

Reputation: 1521

You can't use a rule to specify the parent class name to search for, but you could use a macro.

For example, if you wand to keep the above macro code generic so that it would work with any substitute class name you could write it this way:

function crawlByClassName () {
    var el = {{element}};
 
    while (el && el !== document.body && el.className !== '{{parent class}}') {
        el = el.parentElement;
    }
 
    return el.className === '{{parent class}}';

Then you could create a macro named "parent class" and set the value to the class name you wanted to find. If you wanted to set the name of the parent class based on different conditions, you could use a Lookup Table macro type.

Upvotes: 1

Related Questions