创建< div>并附加< div>动态 [英] Create <div> and append <div> dynamically

查看:133
本文介绍了创建< div>并附加< div>动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态创建< div> ,其中附加了< div> 。到目前为止我有这个工作:

I am trying to create a <div> dynamically, with an appended <div> inside. I have this so far which works:

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

我在创建第二个div并将第二个div附加到第一个div时遇到了麻烦。

I am just having trouble creating and appending the second div to the first div.

我基本上希望将此作为最终加价:

I essentially want to do this as the final markup:

<div id="block" class="block">
   <div class="block-2"></div>
</div>


推荐答案

使用相同的流程。你已经有变量 iDiv ,它仍然引用原始元素< div id ='block'> 你已经创造了。您只需创建另一个< div> 并调用 appendChild()

Use the same process. You already have the variable iDiv which still refers to the original element <div id='block'> you've created. You just need to create another <div> and call appendChild().

// Your existing code unmodified...
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

// Now create and append to iDiv
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

http://jsfiddle.net/W4Sup/1/

事件创建的顺序不一定如上所述。您可以将新的 innerDiv 附加到外部div,然后再将它们添加到< body>

The order of event creation doesn't have to be as I have it above. You can alternately append the new innerDiv to the outer div before you add both to the <body>.

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';

// Create the inner div before appending to the body
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

// Then append the whole thing onto the body
document.getElementsByTagName('body')[0].appendChild(iDiv);

这篇关于创建&lt; div&gt;并附加&lt; div&gt;动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆