I am trying to create a custom javascript in Google Tag Manager to return the p class text element whenever a specific button is clicked within the div. But my script keeps returning the same initial value.
In GTM, I set the trigger element click based on class "myButton". and for the variable, I have this custom javascript code.
function ()
{
var x = document.getElementsByClassName("test-here")[0].innerHTML;
return x;
}
HTML:
<div id = "mydivd1" class = "test">
<p class = "test-here"> I want to return this text 1</p>
<button class = "mybutton"></button>
</div>
<div id = "mydiv2" class = "test">
<p class = "test-here"> I want to return this text 2</p>
<button class = "mybutton"></button>
</div>
How do I return the correct p text element based on the current button class clicked?
Rather than using document in the function, use the relative context of the button.
function (e)
{
var x = e.target.parentNode.getElementsByClassName("test-here")[0].innerHTML;
return x;
}