-1

What i'm trying to accomplish is to find if the click element has a h2 tag, if not, then move to the parent and perform the same check until a value is found and return the value.

When the href link is clicked, I need Google Tag Manager to set the parent h2 text as the variable so it can be used in Event Tracking.

Edit: I cannot use jQuery code for this sorry.

Here's an extract of the HTML code;

<div id="contentRight" class="right">
  <div class="widget blue">
      <h2>Link Title</h2>
    <div style="clear:both;">
      <a href="https://www.websitelink.com" class="buttonOrange" target="_self" >Find out more 
        <i class="fa   fa-chevron-right" aria-hidden="true"></i>
      </a>
    </div>
  </div>
</div>
  

After spending a few hours looking at various post all over the internet, I currently have a mash up of code that isn't working;

function(){    
  var element = {{Click Element}};
    while(element.querySelector('h2').innerText === undefined);
 {
     element = element.parentNode;
 }
 return element.querySelector('h2').innerText;}

Can anyone shed some light on what i'm doing wrong, or provide some suggestion how this may be done?

Jayse
  • 1
  • 2

1 Answers1

0

You seem to be going about it in an awkward way, but if I'm understanding your ask, what you are after is the h2 text for any link that is a child of that element. So, assuming you have jQuery loaded, t would require a simple custom JS tag that would look similar to this:

function(){
   var ce = {{Click Element}};
   return $(ce).closest('#contentRight').find('h2').text().trim()
}

That should return the title for the link, ie. "Link Title".

nyuen
  • 8,829
  • 2
  • 21
  • 28
  • Thank you so much for your answer, but unfortunately jQuery won't be used in this instance. Is there a JavaScript alternative to the jQuery code? – Jayse Jun 23 '16 at 02:56
  • Unfortunately this question is closed, but the links provided should guide you on how to implement the custom JS without jQuery. – nyuen Jun 23 '16 at 03:19