【JavaScript】append, prepend, insertBeforeの違いは?DOM要素を追加するメソッド比較

JavaScriptで画面に新しい要素(HTML)を追加したい時、どのメソッドを使っていますか? append()、appendChild()、prepend()、insertBefore() など、JSには要素を追加するためのメソッドが複数用意されています。

「最後に追加するのか、最初に追加するのか、それとも特定の要素の前に追加するのか」といった挿入位置の違いだけでなく、実は「テキスト(文字列)を直接追加できるか」といった細かな仕様の違いもあります。

今回は、それぞれのメソッドで追加した要素が「どこに・どのように」配置されるのかがひと目でわかるデモと一緒に、各メソッドの正しい使い分けを解説します!

デモ動作

See the Pen JSでDOM要素を追加!append, prepend, insertBeforeの違いと使い分け by mikanbako (@mikanbako) on CodePen.

全画面でのデモ動作は以下のリンクからご確認下さい!(別タブで開かれます)

実装コード紹介

【HTML】

<div class="l-wrap">
  <h2>DOM要素の追加 比較デモ</h2>
  <p class="p-desc">ボタンを押すと、リストに色付きの要素が追加されます!</p>
  
  <div class="p-demo-box">
    
    <!-- 操作ボタン群 -->
    <div class="c-btn-group">
      <button class="c-btn c-btn--append js-btn" data-type="append">append()</button>
      <button class="c-btn c-btn--appendChild js-btn" data-type="appendChild">appendChild()</button>
      <button class="c-btn c-btn--prepend js-btn" data-type="prepend">prepend()</button>
      <button class="c-btn c-btn--insert js-btn" data-type="insertBefore">insertBefore()</button>
    </div>
    <button class="c-btn c-btn--reset js-btn-reset">🔄 リストをリセット</button>

    <!-- アイテムが追加されるリスト -->
    <ul class="c-list js-list">
      <!-- 💡 insertBefore用の基準となる要素 -->
      <li class="c-list__item c-list__item--base js-base-item">【基準アイテム】ここが真ん中です</li>
    </ul>

  </div>
</div>

【CSS】

/* ベース装飾 */
.l-wrap {
  padding: 40px 20px;
  max-width: 600px;
  margin: 0 auto;
  color: #3e3e3e;
  text-align: center;
}

h2 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #1bb4d4;
}

.p-desc {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.p-demo-box {
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgb(0 0 0 / 5%);
}

/* ボタングループ */
.c-btn-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  margin-bottom: 15px;
}

.c-btn {
  padding: 10px 15px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  cursor: pointer;
  border-radius: 6px;
  transition: 0.2s;
}

.c-btn:hover {
  opacity: 0.8;
  transform: translateY(-2px);
}

/* 各ボタンの色 */
.c-btn--append {
  background: #ff9800;
}

.c-btn--appendChild {
  background: #4caf50;
}

.c-btn--prepend {
  background: #00bcd4;
}

.c-btn--insert {
  background: #9c27b0;
}

.c-btn--reset {
  margin-bottom: 15px;
  background: #6c757d;
}

/* リストと追加されるアイテムの装飾 */
.c-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.c-list__item {
  padding: 15px;
  font-size: 16px;
  font-weight: bold;
  border: 2px solid;
  border-radius: 8px;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 基準アイテムと追加アイテムの色分け */
.c-list__item--base {
  color: #666;
  background: #eee;
  border-color: #ccc;
}

.c-list__item--append {
  color: #e65100;
  background: #fff3e0;
  border-color: #ff9800;
}

.c-list__item--appendChild {
  color: #1b5e20;
  background: #e8f5e9;
  border-color: #4caf50;
}

.c-list__item--prepend {
  color: #006064;
  background: #e0f7fa;
  border-color: #00bcd4;
}

.c-list__item--insert {
  color: #4a148c;
  background: #f3e5f5;
  border-color: #9c27b0;
}

【JavaScript】

// DOMの取得
const list = document.querySelector('.js-list');
const buttons = document.querySelectorAll('.js-btn');
const resetBtn = document.querySelector('.js-btn-reset');
let baseItem = document.querySelector('.js-base-item');

// 各ボタンをクリックしたときの処理
buttons.forEach(btn => {
  btn.addEventListener('click', () => {
    const methodType = btn.dataset.type; // どのボタンが押されたか取得
    
    // 1. 新しい <li> 要素を作成
    const newItem = document.createElement('li');
    // 2. デザイン用のクラスを付与(c-list__item--append など)
    newItem.classList.add('c-list__item', `c-list__item--${methodType}`);
    // 3. テキストを設定
    newItem.textContent = `${methodType} で追加されました!`;

    // 💡 4. メソッドに応じて要素を追加!
    if (methodType === 'append') {
      // リストの一番「最後」に追加
      list.append(newItem);
    } 
    else if (methodType === 'appendChild') {
      // リストの一番「最後」に追加(古くからある厳密な書き方)
      list.appendChild(newItem);
    } 
    else if (methodType === 'prepend') {
      // リストの一番「最初」に追加
      list.prepend(newItem);
    } 
    else if (methodType === 'insertBefore') {
      // 「基準アイテム」の直前に追加
      list.insertBefore(newItem, baseItem);
    }
  });
});

// リセット処理(中身を初期状態のHTMLで上書きしてリセット)
resetBtn.addEventListener('click', () => {
  list.innerHTML = '<li class="c-list__item c-list__item--base js-base-item">【基準アイテム】ここが真ん中です</li>';
  // 基準アイテムを作り直したので、JS側の変数も再取得しておく
  baseItem = document.querySelector('.js-base-item');
});

コードの解説と各メソッドの違い

最後に追加する:append() と appendChild()

どちらも親要素の中の「一番最後」に追加するメソッドです。

appendChild() は古くからあるメソッドで「Nodeオブジェクト(作成したHTML要素など)」しか追加できませんが、新しいメソッドである append() は「複数の要素」や「単なる文字列(テキスト)」も直接追加できるという特徴があります。現代の開発では、より柔軟な append() がよく使われます。

応用:appendChild() は「追加した要素」を返してくれる!

append() は返り値が undefined(何も返さない)ですが、appendChild() は「追加した要素そのもの」を返り値として返してくれます。 これを利用すると、要素を追加した直後に、そのまま変数を使ってクラスを付けたりアニメーションを発火させたりする処理がスッキリ書けます!

const list = document.querySelector('.js-list');
const newItem = document.createElement('li');
newItem.textContent = '新しいアイテム';

// 追加と同時に、返ってきた要素を変数「addedItem」で受け取る
const addedItem = list.appendChild(newItem);

// 受け取った要素に対して、すぐに追加の操作(クラス付与など)ができる!
addedItem.classList.add('is-active');
addedItem.style.color = 'red';

最初に追加する:prepend()

親要素の中の「一番最初(先頭)」に追加するメソッドです。

指定した場所に追加する:insertBefore()

親要素.insertBefore(追加したい新要素, 基準となる要素) という書き方をします。 単純な最後・最初ではなく、「リストの中のこのアイテムの直前に入れたい!」という細かい位置指定が必要な時に使用します。

応用:insertBefore() を使って insertAfter を実現するテクニック

「この要素の直後に追加したい」という場合、残念ながらJavaScriptには標準で insertAfter() というメソッドが存在しません。 しかし、insertBefore() と nextElementSibling(次の兄弟要素) を組み合わせることで、全く同じ動きを実現できます!

// 基準となる要素を取得
const targetItem = document.querySelector('.js-target-item');
const newItem = document.createElement('li');
newItem.textContent = '基準アイテムの直後に追加!';

// 💡 基準アイテムの「次の要素」の【直前】に追加する=「直後」になる!
targetItem.parentNode.insertBefore(newItem, targetItem.nextElementSibling);

もし targetItem がリストの最後だった場合、nextElementSibling は null になります。insertBefore の第2引数に null を渡すと、自動的に「一番最後に追加する動作」になるため、エラーにならず機能するスマートなテクニックです!

補足:公式ドキュメント

・MDN: append()
・MDN: appendChild()
・MDN: prepend()
・MDN: insertBefore()
・MDN: nextElementSibling

まとめ

今回はDOM要素を追加する4つのメソッドをご紹介しました。

追加したい場所が「一番最後」「一番最初」「特定の要素の前」のどれに当てはまるかで、適切なメソッドを選択します。

また、append() や prepend() は比較的新しいメソッドのため、文字列を直接挿入できたりと直感的に書きやすくなっています。状況に応じて使い分け、思い通りにHTMLを操作できるようになりましょう!

Prev
Next