JavaScript側からHTMLに要素を追加します。
html側はbodyが空だったとします。
const h1 = document.createElement('h1');
h1.textContent = 'title';
document.body.appendChild(h1);
まずはh1を宣言。
そこに文字列titleを入れて、
appendChild
で追加する。
このbody.appendChild
はbodyの最後に追加するというもの。
bodyの子要素としてappend(追加する)ということですね。
続いてpも入れましょう。
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の間に書くのではなく
指定して差し込む。
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のコピーを挿入する。書き方は
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>
となる)中身は別のものを用意して側だけ流用したい時に使ったりします。
では続いて要素の削除です。要素の削除は親要素から指定する。
document.body.removeChild(h2);
こうすることで、bodyの中の子要素(h2)を削除する、ということになる。