I need a variable in Google Tagmanager which returns the innerhtml of a clicked class. Since there are more elements with this class I have to add an event listener to the classes and return the innerhtml of the clicked element.
Unfortunately my code keeps returning 'undefined'.
document.querySelectorAll(".myclass").foreach(function (item) {
item.addEventListener("click", function(event) {
return event.innerHTML;
})
})
Okay, so a variable that returns inner html of a clicked element (you don't click classes, you click elements).
Make a click trigger where you would use whatever CSS selector you need it to work for.
Make a Custom JS variable like so:
return {{Clicked Element}}.innerHTML;
Now you can make a tag where you would use your trigger and your CJS variable.
No need to add your own event listeners when GTM is perfectly capable of doing it for you. While you certainly still can add your event listeners and pass the data from them to GTM through the dataLayer, you're increasing the complexity needlessly.