0

I have been playing around with GTM for some time, but now I got stuck.

I need to get parent div of clicked element () which contains H4 tag -- and then take text within H4 and pass it 'Event Action'.

So far I have setup click listener, but I am not sure how to use {{element}} within as jQuery selector?

Any tips/ideas? Or am I doing this completely wrong? :-)

Below is DOM structure that illustrates what gets clicked and what I need to grab by GTM macro:

enter image description here

Petr Havlik
  • 3,307
  • 1
  • 19
  • 17

2 Answers2

0

I'm not sure how JQuery would fit into this, but you can grab that value with a custom macro (of Data Layer type in GTM). You can go up and down the DOM starting with gtm.element, which is the element that is clicked on. Does something like this work for data variable name?

gtm.element.parentNode.parentNode.firstChild.firstChild.innerText

Kind of specific to your exact situation, but it should get the job done.

wils484
  • 275
  • 1
  • 3
  • 14
0

I thought of the same thing as @wils484, but thought I would do something a bit more flexible:

function(){

    //define element that was clicked
    var element      = {{gtm.element}};

    //define class
    var elementClass = 'border-box';

    /*go up the DOM tree and as long as there are still elements and
     *they do not contain the class name that contains our elementClass
     *that holds our h4 tag, keep moving. This should be good to go 
     *for earlier IE's.
     */

    while(element && !((" " + element.className + " ").indexOf(" " + elementClass + " ") > -1)){

        element = element.parentNode;
    }

    //find our h4 tag and grab the innerText, or if IE, grab textContent
    return element.querySelector('h4').innerText || element.querySelector('h4').textContent;
}

I'm newer to js and spent some time on this this past week, and even posted a bounty for trying to figure out how to find the class. There are some alternative options in that post Check for class in element in while loop in javascript, but felt that the response I got from @Greg Burghardt (slightly tweaked for earlier versions of IE) made the most since for GTM.

Community
  • 1
  • 1
Blexy
  • 9,573
  • 6
  • 42
  • 55