This is a follow up of Tag Manager Variable from a parent of click element (toggle)
I want to fire a GA4 event on a toggle click where the code is this:
I had to change the css - Selector to div[data-test-id^="is"],div[data-test-id^="is"] *
because I noticed that only clicks right on the button worked. If you click on the untoggled part it would set the toggle but wouldn't fire the event.
So I had to adapt the js variable for the toggles name as well but that didn't work:
function(){
var dataTestID;
if({{Click Element}}.parentElement.getAttribute("data-test-id") == null)
{dataTestID = {{Click Element}}.getAttribute("data-test-id")
;}
dataTestID = {{Click Element}}.parentElement.getAttribute("data-test-id");
return dataTestID;
}
Could you identify the problem?
I assume you are having problem like
<div class='a' data-test-id="test">
<div class='b'>
<button class='c'></button>
</div>
</div>
So if you click the div with class=b, it will work because its parent element is div.a with data-test-id attribute.
But if you click the button element it won't work because its parent element is div.b?
In this case you can change the code parent to closest()
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
This might help the code to get the data-test-id
when the your click div.b or button