Create <div> and append <div> dynamically
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);
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/
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);