创建<ins>元素,用于在加载时进行广告,不带JQuery

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

本文关键字:不带 JQuery 用于 ins lt gt 元素 创建 加载      更新时间:2023-09-26

通常,谷歌广告可以在HTML文档中声明如下:

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

但是,我需要在加载页面时有条件地插入该广告元素。如何在Javascript中动态创建这样一个<ins>元素?我正在寻找一个没有JQuery的代码示例。

显然,以下操作完成了任务:

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