Search code examples
javascriptgoogle-tag-managergetelementsbyclassnamegetelementsbytagnameparent-node

How can I extract the text next to an image with Google Tag Manager?


Here's the challenge:

Code Excerpt

We have an image and text that describes it all nested in the same div. When somebody clicks on that image, we want Google Tag Manager to return that text.

Basically, we need to:

  1. Go up 3 parent nodes
  2. Go down to the child node with the class "right-section"
  3. Go down to the child node with the class "is-title"
  4. Go down to the child node with the tag "a"
  5. Extract the text

Using my crude, self-taught Javascript knowledge, I came up with this monstrosity of a function:

function(){
  return el.parentNode.parentNode.parentNode.getElementsByClassName("right-section")[0].getElementsByClassName("is-title")[0].getElementsByTagName("a")[0].innerText;
}

... which does not work at all.

Any suggestions?


Solution

  • Here's what ultimately worked, for anyone Googling this:

    function (){
         el = {{Click Element}};
         var item = el.parentElement.parentElement.nextElementSibling.getElementsByTagName('a')[0].innerText;
         return item;
    }