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

171 views Asked by At

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.

1

There are 1 answers

0
Jérôme Verstrynge On BEST ANSWER

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);