Search code examples
javascriptgoogle-tag-manager

.closest function returns 'undefined' in Google Tag Manager but works in console


With the help from our developer we have attached data-attributes to all elements we want to track, but with the following code the click lands on the a-tag but I want to grab the data-attribute from the p-tag.

 <main id="content" class="page__content">  
  <div class="app-container page__content__wrapper">
   <div class="page_content_block">
    <p data-mng="mian-forgot-primary">
     <a href="https://homepage.com">Text about the homepage</a>
   </p>
  </div>
 </div>
</main>

The following function works in console (Brave browser and Chrome). I'm simulating a click like a user would do on the site, when clicking the link. The .closest() function looks up the DOM for the p-tag and from there should extract the attribute data-mng. In console i get the output i want the "mian-forgot-primary" value.

$0.addEventListener('click', (e) => {
 e.preventDefault();
const a = e.target.closest('p');
const mng = a.getAttribute('data-mng');
console.log(mng);
});

I have then tried to implement it as a function in Google Tag Manager as a custom javascript variable with the following function. When previewing in Google Tag Manager and clicking on the link (the simulation from before) i just get the value 'undefined' and i don't see why it isn't working for me?

Looking at the documentation i thought that the .closest() function "traverses the element and its parents until it finds a node that matches the provided selector string"?

function(){
 var gtmMng = event.target.closest('p').getAttribute('data-mng');
 return gtmMng;
}

Solution

  • GTM doesn't give you the typical exposure to the event that you get in your normal event callbacks. Instead, you have to go to your built-in GTM variables and enable the Click Element var. Then you can use it as you would use the event.target in the case of click trigger.

    Also use the GTM preview variables debugger to make sure you're not running in timing issues. They're unlikely with the click rules though, so the code below should work after you enable the Click Element var.

    function(){
     return {{Click Element}}.closest('p').dataset.mng;
    }