简体   繁体   中英

Replace html content with Javascript in GTM

Trying to replace "sofort lieferbar" with "Lieferung auf Bestellung" with javascript if class "availability stati13" in Google Tag Manager.

<div class="availability stati13" style="">
sofort lieferbar

            <div class="blueinfo">
        <div style="display: none; opacity: 1;">in den nächsten Tagen Versandbereit</div>
    </div>
</div>

The Javascript itself works fine, but in GTM, nothing happens if fired with a custom html tag.

 <script type="text/javascript"> function myFunction() { var str = document.querySelector(".availability.stati13").innerHTML; var res = str.replace("sofort lieferbar", "Lieferung auf Bestellung"); document.querySelector(".availability.stati13").innerHTML = res; } </script>

Does someone know, why this script in gtm isn't working?

GTM works fine, i tried this one:

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

That would work, but i can't create the if class requirement

You define a function myFunction() but where do you execute it? Maybe you should write it as a self executing function:

(function(){
    // your code here ...
})();

Also make sure to have this tag execute on Dom ready (in order for your code to find the elements you are looking for)

dom-ready-trigger-in-google-tag-manager-quick-guide/

Also the line document.querySelector(".availability.stati13") will return only the first element.. If there are multiple DOM elements with this class you have to handle this for all of them with querySelectorAll .

var elements = document.querySelectorAll(".availability.stati13");    
for (i = 0; i < elements.length; ++i) {
  var str = elements[i].innerHTML;
  elements[i].innerHTML = str.replace("sofort lieferbar", "Lieferung auf Bestellung");
}

I used for instead of forEach for maximum compatibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM