0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

初心者によるJavaScriptによる要素生成・削除などの学習

Last updated at Posted at 2019-08-25

JavaScript側からHTMLに要素を追加します。

html側はbodyが空だったとします。

main.js
const h1 = document.createElement('h1');
h1.textContent = 'title';
document.body.appendChild(h1);

まずはh1を宣言。
そこに文字列titleを入れて、
appendChildで追加する。

このbody.appendChildはbodyの最後に追加するというもの。
bodyの子要素としてappend(追加する)ということですね。

続いてpも入れましょう。

main.js
const h1 = document.createElement('h1');
h1.textContent = 'title';
document.body.appendChild(h1);

const p = document.createElement('p');
p.textContent = 'text text text text text ';
document.body.appendChild(p);

こうすると、pはh1よりもあとに配置される。
(ここにhtmlだとどう出てくるか表示したいのですが、Qiitaのチートシートを見てもよくわかりませんでした)

さらにh1とpの間にh2を追加してみる。
単純にjsファイルのh1とpの間に書くのではなく
指定して差し込む。

main.js
const h1 = document.createElement('h1');
h1.textContent = 'title';
document.body.appendChild(h1);

const p = document.createElement('p');
p.textContent = 'text text text text text ';
document.body.appendChild(p);

const h2 = document.createElement('h2');
h2.textContent = 'subtitle';
document.body.insertBefore(h2, p);

差し込む場合はinsertBeforeを使う。第一引数に追加する要素、第ニ引数にどこの前に入れるかを指定する。上記の場合はpの前にh2を入れろということですね。こうすることで、要素をh1,h2,pと並べることができた。
※ちなみにinsertAfterは存在しないらしい

では続いて、h1の後にpのコピーを挿入する。書き方は

main.js
const h1 = document.createElement('h1');
h1.textContent = 'title';
document.body.appendChild(h1);

const p = document.createElement('p');
p.textContent = 'text text text text text ';
document.body.appendChild(p);

const h2 = document.createElement('h2');
h2.textContent = 'subtitle';
document.body.insertBefore(h2, p);

const copy = p.cloneNode(true);
document.body.insertBefore(copy, h2);

p.cloneNode(true)とすることでp要素をまるごとコピーできる。
挿入場所はh1の後なので、h2の前、つまりinsertBefore(copy, h2);とする。

ちなみにこれをp.cloneNode(false)にすると、pの中身(子要素)はコピーせずにp要素だけコピーする。(ここだと<p></p>となる)中身は別のものを用意して側だけ流用したい時に使ったりします。

では続いて要素の削除です。要素の削除は親要素から指定する。

main.js
document.body.removeChild(h2);

こうすることで、bodyの中の子要素(h2)を削除する、ということになる。

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?