問題一覧に戻る
中級dom
問題107: appendChild

appendChildメソッドによるDOM要素の追加を学びましょう。appendChildは親要素に子要素を追加する最も基本的なメソッドで、指定した要素を親要素の最後の子として追加します。既に別の場所に存在する要素を追加した場合、その要素は移動されます(コピーされません)。動的なリストやテーブルの構築、フォーム要素の動的追加など、DOM操作の中核となるメソッドです。

const parent = {
children: [],
appendChild: function(child) {
this.children.push(child);
}
};

const child1 = { id: 1 };
const child2 = { id: 2 };

parent.(child1);
parent.(child2);

console.log(parent.children.length);
parent.children.forEach(c => console.log(c.id));