Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 973
Fredy31 Avatar asked Mar 19 '26 20:03

Fredy31


2 Answers

Seems the Click Element variable works great here. It was weird, I was using it in '' and that made it return only the url. But you can use it like a this

function(){
    var title = jQuery({{Click Element}}).parent().find('h2').html();

    return title;
}
like image 190
Fredy31 Avatar answered Mar 21 '26 11:03

Fredy31


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.

like image 45
Justin Avatar answered Mar 21 '26 09:03

Justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!