我正在尝试创建一个
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
我只是在创建第二个div并将其附加到第一个div时遇到问题。
基本上,我想将此作为最终标记:
<div id="block" class="block">
<div class="block-2"></div>
</div>
使用相同的过程。您已经有了变量iDiv
,它仍然引用原始元素
// 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
添加到
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);
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
var div2 = document.createElement('div');
div2.className = 'block-2';
iDiv.appendChild(div2);
var iDiv = document.createElement('div'),
jDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
jDiv.className = 'block-2';
iDiv.appendChild(jDiv);
document.getElementsByTagName('body')[0].appendChild(iDiv);