Google Tag manager - Get parent of element in a javascript variable

时光怂恿深爱的人放手 提交于 2019-12-22 17:06:35

问题


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.


回答1:


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;
}



回答2:


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.




回答3:


With Jquery, you can do something like this

$('a').click(function(){
 var h2Content = $(this).siblings('h2').text();
 console.log(h2Content);
});

Be carefull, this code will put a click event handler on all tags.



来源:https://stackoverflow.com/questions/44315069/google-tag-manager-get-parent-of-element-in-a-javascript-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!