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;
}