0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】DOM操作の基本!createElementで作る動的なコメントフィード

0
Posted at

JavaScriptを使って新しいHTML要素を直接生成し、画面に追加する 「動的要素の生成(DOM操作)」 について学びました。
掲示板やSNSでよく使われる「コメント登録・削除」機能を例に、その仕組みを整理してみます。

1. DOM要素の動的生成:createElement

// 1. タグの生成
const newItem = document.createElement('li');

// 2. 属性や内容の設定
newItem.className = 'comment-box';
newItem.textContent = 'こんにちは!';

// 3. 親要素に組み立てる
commentList.appendChild(newItem);

2. 要素の組み立て(appendChild)

今回のコードのポイントは、複数の <span><button> を一つの <li> の中に順番に積み上げていく「組み立て」の工程です。

  • 作成者(span) を生成・設定

  • コメント内容(span) を生成・設定

  • 削除ボタン(button) を生成して削除 技能

  • これらをすべて 親要素(li) に appendChild で追加

3. 動的要素へのイベント割り当て

createElement で作ったボタンには、生成されるのと同時に機能を割り当てることができます。

deleteBtn.onclick = function() {
    newItem.remove(); // 自分自身(li)を削除
    getCommentCount(); // 全体の件数を更新
};

要素が作られるたびにイベントがセットされるため、非常に直感的です。

4. 子要素の数を確認する:children.length

コメントが追加・削除されるたびに、現在のリストにいくつの項目があるかを children.length で確認し、画面に反映させます。

function getCommentCount() {
    const commentList = document.getElementById("commentList");
    // commentListの子要素(li)の数を取得して画面に表示
    count.textContent = commentList.children.length;
}

まとめ

  • Vanilla JSの魅力: ライブラリを使わず、純粋なJavaScriptだけで要素を一から組み立てることで、ブラウザがどのようにHTMLを解釈して動かしているのか、その原理を深く理解できました。

  • ロジックの分離: コメントの「件数を数える処理」を一つの関数(getCommentCount)にまとめることで、追加時と削除時の両方で再利用できる効率的なコードが書けました。

DOM操作に慣れると、画面上のあらゆる要素を自分の思い通りにコントロールできるので、開発がどんどん楽しくなります!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?