#GTMTips: add HTML elements to the page programmatically – News Couple

#GTMTips: add HTML elements to the page programmatically

One annoying quirk of Google Tag Manager is that it removes any non-standard HTML attributes from the elements you add to your custom HTML tags. I’m using “non-standard” as a qualifier here, because I don’t have an exhaustive list of attributes that are being ignored. but at least data attributes (for example data-id) and attributes with custom names (such as aria-labelledby) is either stripped on injection, or GTM may actually prevent you from saving the container if your custom HTML tag contains elements with these attributes.

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


Simmer . Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava right in your inbox!

Tip 73: Add items to the page programmatically

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

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

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

The component that failed to inject

As you can see, the data attribute is stripped.

Here is another example. Let’s say you have an element that looks like this:

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

This will not even allow you to save the container. You will see an error message like this:

Invalid form error with custom HTML tag

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

So, here are the files solution. Uses JavaScript While that! You can rewrite the custom HTML tag to add the element to the page using JavaScript, so you can add any custom attributes you want.

Here’s how it works.

    // 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 the DOM methods of the JavaScript. All themes are added with the extension setAttribute() method, and finally the element is added to the end <body>.

It’s kind of overhead compared to adding the element directly to the custom HTML tag, but the end result is cleaner, since you have complete control over what attributes are added to the element, and where they are added to the page.


Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button