1. ホーム
  2. javascript

[解決済み] Create <div> and append <div> dynamically

2022-05-26 03:43:20

Question

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);

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>

How to solved?

Use the same process. You already have the variable iDiv which still refers to the original element <div id='block'> you've created. あなたはただ、別の <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);