如何将动态创建的div附加到另一个动态创建的div?

时间:2021-02-13 21:18:23

I'm trying to add a dynamically created div to another dynamically created div, but I keep getting an error in the Chromium JavaScript console that says "Cannot Call method appendChild of undefined. I'm not sure why this is happening. Here is the code that I used:

我正在尝试将动态创建的div添加到另一个动态创建的div中,但我在Chromium JavaScript控制台中不断收到错误,该错误表示“无法调用方法appendChild of undefined。我不知道为什么会发生这种情况。这是我用过的代码:

for(var i=3; i < 8; i++)
{
      var parent_div = document.createElement('div');
      parent_div.setAttribute('class',"bottom_block left");
      document.body.appendChild(parent_div); //Append parent_div to body. This works fine

      var child_div = document.createElement('div');
      child_div.setAttribute('class', "content SA");
      child_div.setAttribute('id', "SA"+i);
      document.parent_div.appendChild(child_div); // This is 
 }

1 个解决方案

#1


5  

Instead of document.parent_div.appendChild() use parent_div.appendChild().

而不是document.parent_div.appendChild()使用parent_div.appendChild()。

document.parent_div is looking for the parent_div property of the document whereas parent_div is the variable referencing the div you just added.

document.parent_div正在查找文档的parent_div属性,而parent_div是引用刚刚添加的div的变量。

#1


5  

Instead of document.parent_div.appendChild() use parent_div.appendChild().

而不是document.parent_div.appendChild()使用parent_div.appendChild()。

document.parent_div is looking for the parent_div property of the document whereas parent_div is the variable referencing the div you just added.

document.parent_div正在查找文档的parent_div属性,而parent_div是引用刚刚添加的div的变量。