質問

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.

役に立ちましたか?

解決

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); 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top