Google Tag manager - Get parent of element in a javascript variable

Viewed 7299

In a custom javascript variable, how can you get the parent element of the clicked element?

<div>
    <h2>Lorem Ipsum</h2>
    <a href="#"></a>
</div>

For instance, I want to go get the content of the <H2> when I click the <a> to log Lorem Ipsum when the <a> is clicked.

3 Answers

I know this is an older question but while searching for this exact problem myself, I found this really helpful link with a solution.

You can add custom variables. To do this, in Google Tag Manager go to Variables, under User-Defined Variables click on New. Select Variable Type of Custom JavaScript, name it Find Closest and past the following code:

function() {
  return function(target, selector) {
    while (!target.matches(selector) && !target.matches('body')) {
      target = target.parentElement;
    }
    return target.matches(selector) ? target : undefined;
  }
}

Add another JavaScript Variable for your specific case. Something like:

function() {
    var parentElement = {{Find Closest}}({{Click Element}}, 'div'),
        childElement = typeof parentElement !== 'undefined' ? parentElement.querySelector('h2') : undefined;
    return typeof childElement !== 'undefined' ? childElement.innerText : undefined;
}

Note: You can add a polyfill for matches for older browers.

Related