LoginSignup
0
0

More than 1 year has passed since last update.

JavaScript appendChild 親要素に子要素を追加する

Posted at

要素を追加する

以下の要素に子要素を追加する。

<div id="parent">親要素です</div>

1. 親要素のオブジェクトを取得する。

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

2. 子要素のオブジェクトを作成する。

const child = document.createElement('div');

3. 親要素のオブジェクトのappendChildメソッドに、子要素のオブジェクトを渡す。

parent.appendChild(child);

子要素の追加される場所

子要素は親要素の末尾に追加される。例えばfor文で続けて子要素を追加してみると、以下のような結果になる。

<div id="parent">親要素です</div>
const parent = document.getElementById('parent');
for (let i = 0; i < 5; i++) {
  const child = document.createElement('div');
  child.textContent = String(i) + '番目の子要素です'
  parent.appendChild(child);
}

image.png

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0