ใช้กระบวนการเดียวกัน คุณมีตัวแปรอยู่แล้วiDivซึ่งยังคงอ้างอิงถึงองค์ประกอบดั้งเดิมที่<div id='block'>คุณสร้างขึ้น คุณเพียงแค่ต้องสร้างอีกและโทร<div>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>.
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);
document.bodyเพียงแค่การใช้งาน