#GTMTips: Add HTML Elements to the Page Programmatically

Google Tag Manager's Custom HTML tags strip out any non-standard parameters from HTML elements you add directly to the tag. By addng the elements programmatically, you can work around this limitation.

One of the annoying quirks of Google Tag Manager is that it strips out any non-standard HTML attributes from elements you add to Custom HTML tags. I’m using “non-standard” as a qualifier here, because I don’t have an exhaustive list of attributes that are ignored. But at least data attributes (e.g. data-id) and attributes with custom names (e.g. aria-labelledby) are either stripped out upon injection, or GTM might actually prevent you from even saving the container if the Custom HTML tag has elements with these attributes.

So this tip might be very useful to you if you want to annotate your custom HTML elements with custom attributes.

Tip 73: Add elements to page programmatically

Here’s the problem. Say you have an element that looks like this:

<script src="/myScript.js" data-simo-script="My Script"></script>

If you add that line to a Custom HTML tag, the actual element that ends up on the page will look something like this:

As you can see, the data attribute is stripped out.

Here’s another example. Say you have an element that looks like this:

<input type="text" aria-labelledby="firstname"/>

This won’t even let you save the container. You’ll see an error message like this:

This is unfortunate, because there might be good reason to add these custom attributes to your elements.

So, here’s the solution. Use JavaScript instead! You can rewrite the Custom HTML tag to add the element to the page using JavaScript, and thus you can add any custom attributes to it that you want.

Here’s how it works.

  (function() {
    // Change 'script' to whatever element you want to create, e.g. 'img' or 'input'.
    var el = document.createElement('script');
    // Add any standard attributes you need, e.g. 'src', 'width', 'type', 'name'.
    // The syntax is el.setAttribute(attribute_name, attribute_value).
    el.setAttribute('src', '/myScript.js');
    // Add any non-standard attributes with the same method.
    el.setAttribute('data-simo-script', 'My Script');
    // Finally, inject the element to the end of <body>

Here you create the element using JavaScript’s DOM methods. All attributes are added with the setAttribute() method, and finally the element is added to the end of <body>.

It’s a bit of an overhead compared to adding the element directly to the Custom HTML tag, but the end result is cleaner, since you have full control over what attributes are added to the element, and where in the page it is added to.

Try it out!