How to get data attribute in Custom JavaScript variable?

A value from an elements data attribute (data-category) needs to be read when firing the tag. I tried to create a variable of Custom JavaScript type.

With element.getAttribute('data-category') it could be easily read. But what is the scope the called function is running in to get a reference to the element?

I found out, the custom function gets two variables as parameters: parameters and TagManager.
But I couldn’t find any reference of the current element to call getAttribute() on it.

I also tested a tag manager variable of type DOM Element. This could get the custom data attribute, but it just returns the value of the first matching element. This is quite useless as there are multiple elements of the same class on the page.

It seems the first approach is quite close to the solution. Anyone else using data-attributes and has a hint on this?

Hi Progger, I was really wondering if you found a solution. I was looking into the second solution with DOM element but alas, can’t get it to work.

Hi Max, sorry I haven’t found a solution so far. The Matomo tag manager is well appreciated but it still lacks some basic functionality compared to GTM.

You can use the dataLayer to access the clicked element:

function () {
 if (TagManager.dataLayer.get('mtm.clickElement')) {
     return TagManager.dataLayer.get('mtm.clickElement').getAttribute('data-foo');
 } else { 
     return '';
 }
}

Worked for me :slight_smile:

1 Like

I wonder if Matomo has anything like GTM has: gtm.element.dataset.name_of_attribute

Which comes in handy as you don’t have to create custom JS function to grab the attribute value.

Has anyone find anything similar to this?

In addition to above it seems tomper00 made a very nice JS script:

Data attribute tracking is a technich that allows you to just set meta data in your code and from that automatically send event tracking to Matomo without having to add triggers, tags and variables in the TagManager

1 Like