Search code examples
javascripthtmlgoogle-tag-manager

Replacing a text inside of a div in GTM


Similar to this question I want to change some text inside a dynamic div. The explanation there didn't work for me so I started a new thread (rep too low to comment). What makes this div "dynamic" is a some script that calculate how much money you need to spend (based on added to cart items) to get free shipping. The statement I want to replace is always there. I guess you could call it erasing the part of the text. :)

My div:

<div class="free-shipping__content">Brakuje Ci 151,00&nbsp;zł do darmowej dostawy (Paczkomaty InPost).</div>

My code in GTM (loaded on DOM ready):

<script type="text/javascript">
(function(){
  var elements = document.querySelectorALL(".free_shipping__content");    
  for (i = 0; i < elements.length; ++i) {
    var str = elements[i].innerHTML;
    elements[i].innerHTML = str.replace(" (Paczkomaty InPost)", "");
}
})();
</script>

Thanks!

Image of surrounding divs


Solution

    1. Good job on that closure.

    2. document.querySelectorALL is not a function. You meant document.querySelectorAll.

    3. Another problem is your css selector. You're using .free_shipping__content while the actual class name is different. Your selector should be .free-shipping__content

    After these fixes, your code works. However, I already rewrote it to test properly, so I might as well offer a more readable and elegant solution:

    document.querySelectorAll(".free-shipping__content").forEach(function (el) {
      el.innerHTML = el.innerHTML.replace(" (Paczkomaty InPost)", "");
    });