title: Google Tag Manager custom javascript to get data layer variable
body: <p>I want to do some processing on a data layer variable before I want to use it in a tag. for instance I have a number of social icons with the fontawseome framework. Now I want to create a variable that gives me which one is clicked. </p>
  
  <p>How do I get the part of the data layer <code>elementClasses</code> value?</p>
  
  <p>In preview mode I can see that when I click on a button the <code>Data Layer values after this message</code> box looks like this:</p>
  
  <pre><code>{
    gtm: {
      ...
      ...
      elementClasses: 'fa fa-twitter',
      ...
    }
  }
  </code></pre>
  
  <p>I essentially want to make a <code>GTM</code> variable of type <code>Custom JavaScript</code> that does this</p>
  
  <pre><code>function(){
    return elementClassesString.match(/fa-.*/);
  }
  </code></pre>
  
  <p>Any tips?</p>
  
  <p>EDIT::</p>
  
  <p>In the console I can get the latest data layer entry by typing <code>dataLayer[dataLayer.length-1]</code> so I figured this would do the trick:</p>
  
  <pre><code>function(){
    latest = dataLayer[dataLayer.length-1]["gtm.elementClasses"];
    if(latest === ""){
     social = "not-set" 
    }else{
      social = latest.match(/fa-.*/)[0];
      social = social.substring(3,social.length);
    }
    return social;
  }
  </code></pre>
  
  <p>But I only get <code>undefined</code> in the GTM preview. Why is that?</p>