Search code examples
javascripthtmldynamiccreation

Creating an <ins> element for advertising at load time, without JQuery


Typically, a Google ad can be declared as following in a HTML document:

<div id="myAds">
    <ins class="adsbygoogle"
         style="display:inline-block;width:160px;height:600px"
         data-ad-client="ca-pub-1234567890"
         data-ad-slot="0987654321">
    </ins>
</div>

However, I need to insert that ad element conditionally when the page is loaded. How can I create such an <ins> element dynamically in Javascript? I am looking for a code example without JQuery.


Solution

  • Apparently, the following does the job:

        var myAds = document.getElementById("myAds");
    
        var frag, elem;
    
        frag = document.createDocumentFragment();
        elem = document.createElement('ins');
    
        frag.appendChild(elem);
    
        elem.className += "adsbygoogle";
        elem.setAttribute("style", "display:inline-block;width:160px;height:600px");
        elem.setAttribute("data-ad-client", "ca-pub-1234567890");
        elem.setAttribute("data-ad-slot", "0987654321");
    
        myAds.appendChild(frag);