HTMLタブに下のコードを貼り付けてください。
<button id="summonBtn">召喚!</button>
<div id="stage"></div>
JSタブに下のコードを貼り付けてください。
const btn = document.querySelector('#summonBtn');
const stage = document.querySelector('#stage');
btn.addEventListener('click', function() {
// 精霊を作る
const spirit = document.createElement('p');
spirit.textContent = '✨ 精霊が現れた!';
// 削除ボタンを作る
const deleteBtn = document.createElement('button');
deleteBtn.textContent = '消す';
// 削除ボタンを押したら、精霊ごと消える
deleteBtn.addEventListener('click', function() {
spirit.remove();
});
// 精霊の中に削除ボタンを入れて、舞台に出す
spirit.appendChild(deleteBtn);
stage.appendChild(spirit);
});
召喚ボタンをクリックして精霊を増やし、それぞれの「消す」ボタンで個別に削除できることを確認してください。
前の課題のコードに「削除ボタン」を追加したものです。同じ部分は読み飛ばし、新しい部分だけを読み解きましょう。
const deleteBtn = document.createElement('button');
deleteBtn.textContent = '消す';
今度は button タグの部品を作って deleteBtn と名付け、文字を「消す」にしています。
deleteBtn.addEventListener('click', ...):削除ボタンに約束をさせるdeleteBtn.addEventListener('click', function() {
spirit.remove();
});
「deleteBtn(削除ボタン)が押されたら spirit(精霊)を消す」という約束です。
spirit.remove() は「この要素を画面から取り除く」という命令です。
なぜ「自分に対応する精霊」だけが消えるのか
削除ボタンを押したとき、なぜ他の精霊ではなく自分のペアの精霊だけが消えるのでしょうか。
それは、deleteBtn に約束させるとき、同じタイミングに作られた spirit を指定しているからです。召喚ボタンが押されるたびに spirit と deleteBtn のペアが作られ、それぞれが「自分のペア」を覚えています。
spirit.appendChild(deleteBtn):セット商品にするspirit.appendChild(deleteBtn);
stage.appendChild(spirit);
まず削除ボタン(deleteBtn)を精霊(spirit)の中に入れます。その後、精霊ごと舞台(stage)に貼り付けます。
こうすることで「精霊と削除ボタンがセット」になります。spirit.remove() を呼んだとき、精霊の中にある削除ボタンも一緒に消えます。
全体の流れをまとめると:
1. 精霊を作る
2. 削除ボタンを作る
3. 削除ボタンに「押されたら精霊を消す」という約束をさせる
4. 精霊の中に削除ボタンを入れる(セット商品にする)
5. 精霊を舞台に貼り付ける
変える場所は1行だけです。
deleteBtn.textContent = '消す'; ← ここの文字を変える
'消す' の部分を好きな文字に変えてみましょう。例:'✕'、'削除'、'バイバイ'