在div中追加一个div

时间:2018-08-20 18:21:03

标签: javascript html function append

我在HTML页面中有这个。这是一个外部脚本,应将div添加到canvasDiv。

如果我将div附加在正文中,脚本将起作用。但是,如果我希望将其添加到通过函数添加的div中,则似乎无法正常工作。我在哪里错了?

function AdDiv(divname)
    {
        alert("loaded");
        alert(divname);

        //make a div that will be used for the canvas
        var iDiv = document.createElement('div');
        iDiv.id = 'placedCanvas';
        iDiv.className = 'placedCanvas';

        //document.getElementsByTagName('body')[0].appendChild(iDiv);
        document.getElementsByTagName(divname).appendChild(iDiv);
    }
    <div id="canvasDiv"></div>

    <script type="text/javascript" src="https://pixelvaria.com/wp-content/themes/pixelvaria/js/modelscript.js"></script>
    <script>
       AdDiv("canvasDiv");
    </script>

    

3 个答案:

答案 0 :(得分:0)

使用此:

function AdDiv(divId)
{

    //make a div that will be used for the canvas
    var iDiv = document.createElement('div');
    iDiv.id = 'placedCanvas';
    iDiv.classList.add('placedCanvas');

    //append it to the div with the given ID, not name
    document.getElementById(divId).appendChild(iDiv);
}

与此:

<div id="canvasDiv"></div>

<script type="text/javascript" src="https://pixelvaria.com/wp-content/themes/pixelvaria/js/modelscript.js"></script>
<script>
   window.onload = function () 
   {
       AdDiv("canvasDiv");
   }
</script>

答案 1 :(得分:0)

您正在调用错误的Javascript方法。您需要getElementById(因为这就是您要传递给getElementsByTagName的内容:

function AdDiv(divname)
    {
        alert("loaded");
        alert(divname);

        //make a div that will be used for the canvas
        var iDiv = document.createElement('div');
        iDiv.id = 'placedCanvas';
        iDiv.className = 'placedCanvas';

        //document.getElementsByTagName('body')[0].appendChild(iDiv);
        document.getElementsById(divname).appendChild(iDiv);
    }
    <div id="canvasDiv"></div>

    <script type="text/javascript" src="https://pixelvaria.com/wp-content/themes/pixelvaria/js/modelscript.js"></script>
    <script>
       AdDiv("canvasDiv");
    </script>

    

答案 2 :(得分:0)

您应使用document.getElementById通过其id获取一个元素。 document.getElementsByTagName(顾名思义)会返回HTMLCollection个具有特定名称的元素。

<div id="canvasDiv"></div>

    <script type="text/javascript" src="https://pixelvaria.com/wp-content/themes/pixelvaria/js/modelscript.js"></script>
<script>
function AdDiv(divname)
{
        alert("loaded");
        alert(divname);

        //make a div that will be used for the canvas
        var iDiv = document.createElement('div');
        iDiv.id = 'placedCanvas';
        iDiv.className = 'placedCanvas';
        iDiv.textContent = "Div text";

        //document.getElementsByTagName('body')[0].appendChild(iDiv);
        document.getElementById(divname).appendChild(iDiv);
}
AdDiv("canvasDiv");
</script>