Search code examples
javascripthtmlgoogle-tag-manager

How to get the span text using java script to pass it to GA through GTM


I have my piece of code like this on my website :

<span itemprop="productID" data-masterid="MV-20648-BR">20649-BR</span>

In which I need to get the 20649-BR

i have tried using this:

var div = document.getElementByClassName("itemprop");
var spans = div.getElementsByTagName("span");
  alert(spans);

but I was not able to get the text value. can anyone help me !


Solution

  • You tried to interactive with Model Attribute in HTML5, You need create in 'Custom Javascript' Variable:

    From Variables > New > Dom Elemetn

    Name it, then add this code inside it:

    function(){
      
       var masterId = document.querySelectorAll('span[data-masterid]');
       var allmasterId = Array.prototype.map.call(masterId, function(a) { return  a.getAttribute('data-masterid');  });
        
       return allmasterId;
    }
    

    Now you can use this Variable name any where in GTM by {{varibale_name}}.