🧩

📘 JavaScriptでDOM要素を追加・削除・編集するまとめ

に公開1

📘 JavaScriptでDOM要素を追加・削除・編集するまとめ(Zenn投稿用)

このドキュメントでは、ブラウザ上でDOM要素をJavaScriptを使って追加・削除・編集する方法をまとめています。以下のサンプルは、名前・年齢・電話番号を入力してリストに追加し、削除や編集ができる機能を含んでいます。


📌 主要な概念まとめ

1. innerHTML

  • HTML要素の中身をHTMLタグを含んだ文字列で取得・設定できる。
someElement.innerHTML = '<strong>太字のテキスト</strong>'
  • タグがそのまま認識されるため、スタイルの適用が可能。
  • 注意点: 元の内容が全て置き換わるため、ユーザーの入力をそのまま使うとXSSなどのセキュリティリスクがある。

2. textContent

  • HTMLタグを無視してテキストのみ取得・設定する。
someElement.textContent = '<strong>テキスト</strong>' // → 実際にはタグが適用されない
  • display: noneなどの非表示要素も含めたテキストを取得可能。

3. querySelector

  • CSSセレクタの形式で最初に一致した要素1つを取得する。
document.querySelector(".edit-btn")
  • クラス・id・タグなど、CSSの文法をそのまま使える。

4. getElementById

  • HTML内で一致するidの要素を取得する際に使用。
document.getElementById("name")

🛠️ 実装機能の説明

🔹 送信 → 新しいカードを生成

form.addEventListener("submit", function (event) {
  event.preventDefault();

  const entry = document.createElement("div");
  entry.classList.add("entry");
  entry.innerHTML = \`
    <button class="delete-btn">削除</button>
    <button class="edit-btn">編集</button>
    <p><strong>名前:</strong> \${name}</p>
    <p><strong>年齢:</strong> \${age}</p>
    <p><strong>電話番号:</strong> \${phone}</p>
  \`;

  const deleteBtn = entry.querySelector(".delete-btn");
  deleteBtn.addEventListener("click", () => {
    entry.remove();
  });

  const editBtn = entry.querySelector(".edit-btn");
  editBtn.addEventListener("click", () => {
    const ps = entry.querySelectorAll("p");
    const namep = ps[0], agep = ps[1], phonep = ps[2];

    if (editBtn.textContent === "保存") {
      const inputs = entry.querySelectorAll("input");
      const newName = inputs[0].value;
      const newAge = inputs[1].value;
      const newPhone = inputs[2].value;

      namep.innerHTML = `<strong>名前:</strong> \${newName}`;
      agep.innerHTML = `<strong>年齢:</strong> \${newAge}`;
      phonep.innerHTML = `<strong>電話番号:</strong> \${newPhone}`;

      editBtn.textContent = "編集";
    } else {
      const oldName = namep.textContent.replace("名前:", "").trim();
      const oldAge = agep.textContent.replace("年齢:", "").trim();
      const oldPhone = phonep.textContent.replace("電話番号:", "").trim();

      namep.innerHTML = `<strong>名前:</strong> <input value="\${oldName}">`;
      agep.innerHTML = `<strong>年齢:</strong> <input value="\${oldAge}">`;
      phonep.innerHTML = `<strong>電話番号:</strong> <input value="\${oldPhone}">`;

      editBtn.textContent = "保存";
    }
  });

  output.appendChild(entry);
  form.reset();
});

💡 学びのポイント

  • DOM要素はイベント内で生成・操作することでアクセス可能(entryはsubmitイベント内でのみ有効)。
  • querySelector("p")[0] ❌ → querySelectorAll("p")[0]
  • textContentはテキストのみ、innerHTMLはタグも含む。
  • ボタンのテキスト状態で条件分岐すると、トグル動作を実装できる。

✅ まとめ

このサンプルを通じて、DOM操作の基本である要素の選択・イベント登録・innerHTMLtextContentの違い・動的な更新方法まで実際に手を動かしながら理解できます。

Discussion