JavaScriptで子要素を追加する

JavaScriptを使って特定の要素に子要素を動的に追加する方法です。
要素の作成にはdocument.createElement()、子要素の追加には、Node.appendChild()を利用します。

子要素を追加する例

次のdivタグに子要素を追加先する例になります。

<div id="parentDiv"></div>

画像を追加

const parent = document.getElementById('parentDiv');

let img = document.createElement('img');
img.className = 'img-class';
img.src = 'sample.jpg';

parent.appendChild(img);

テキストボックスを追加

const parent = document.getElementById('parentDiv');

let input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('size', "10");

// 読取専用.
let inputReadonly = document.createElement('input');
inputReadonly.setAttribute('type', 'text');
inputReadonly.setAttribute('size', "10");
inputReadonly.readOnly = true;

parent.appendChild(input);
parent.appendChild(inputReadonly);

読取専用は次のような記述もできます。

inputReadonly.setAttribute('readonly', true);

セレクトボックスの要素を追加する

次のセレクトボックスに子要素(項目)を追加先する例です。

<select size="5" id="parentSelect" name="month" style="width: 100px;">
</select>

オプション要素の追加

const select = document.getElementById('parentSelect');

let option = document.createElement('option');
option.value = "1";
option.text = 'January';

select.appendChild(option);
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です