Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert custom HTML in page DOM with Google Tag Manager

I've implemented GTM on my website. I'm wondering if is possible to add custom HTML/JS in a specific position of the DOM.

This is what I've inserted in my page:

<div class="myClass">
    <p>foo</p>
    <script>
        dataLayer.push({'event':'myEvent'})
    </script>   
</div>

and on GTM I've set up a tag with this html:

<div class="test">this is a test</div>
<iframe src="www.foo.com" />

which is triggered on myEvent.

Unfortunatly this is not working correctly, my tag is inserted at the bottom of my web page and not inside the myClass div.

Am I doing something wrong or this is just not allowed by GTM?

Thanks.

like image 707
Lookhill Avatar asked Oct 23 '25 14:10

Lookhill


1 Answers

"Not allowed" is perhaps a bit strong (as you can see it works to some extent), but tags that change visual aspects of the page are generally not recommended.

If you want to insert HTML at a specific location it would be better to create the element dynamically via javascript and append it to an existing element, so your HTML tag would look something like (untested):

<script>
var myDiv = document.createElement('div');
myDiv.setAttribute('class','test');
var container = document.querySelector('.myClass');
container.append(myDiv);
</script>

You would need to make sure that the element you append to is unique (if possible add an id rather than a class name). Tags are executed asynchronously, so it's a bit hard to say at which point in the loading process the HTML is appended (this will cause a reflow in the DOM which is an expensive operation for the client, so you do not want to do this too often).

like image 171
Eike Pierstorff Avatar answered Oct 27 '25 02:10

Eike Pierstorff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!