In a custom javascript variable, how can you get the parent element of the clicked element?
<div>
<h2>Lorem Ipsum</h2>
<a href="#"></a>
</div>
For instance, I want to go get the content of the <H2> when I click the <a> to log Lorem Ipsum when the <a> is clicked.
Seems the Click Element variable works great here. It was weird, I was using it in '' and that made it return only the url. But you can use it like a this
function(){
var title = jQuery({{Click Element}}).parent().find('h2').html();
return title;
}
I know this is an older question but while searching for this exact problem myself, I found this really helpful link with a solution.
You can add custom variables. To do this, in Google Tag Manager go to Variables, under User-Defined Variables click on New. Select Variable Type of Custom JavaScript, name it Find Closest and past the following code:
function() {
return function(target, selector) {
while (!target.matches(selector) && !target.matches('body')) {
target = target.parentElement;
}
return target.matches(selector) ? target : undefined;
}
}
Add another JavaScript Variable for your specific case. Something like:
function() {
var parentElement = {{Find Closest}}({{Click Element}}, 'div'),
childElement = typeof parentElement !== 'undefined' ? parentElement.querySelector('h2') : undefined;
return typeof childElement !== 'undefined' ? childElement.innerText : undefined;
}
Note: You can add a polyfill for matches for older browers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With