LoginSignup
6
4

More than 5 years have passed since last update.

Node.insertBefore を使って insertAfter する

Last updated at Posted at 2017-12-28

生 DOM API では insertBefore はありますが、insertAfter はありません。
ある DOM の1個後ろに新しいアイテムを追加したい場合は、次のように書くことで処理を実現できます。

target.parentElement.insertBefore(newItem, target.nextSibling)

上で、 target は1個後ろにアイテムを追加したい基準の dom です。target が兄弟 dom の中で一番最後のアイテムだったとしても上の書き方で OK です。その場合は、 target.nextSibling が null になって、その場合は insertBefore の仕様で、newItem はリストの中の一番最後に挿入されます。

以下のようなヘルパー関数を作ると便利かもしれません。

insert-after.js
function insertAfter(newItem, target) {
  target.parentNode.insertBefore(newItem, target.nextSibling);
}

参考: https://stackoverflow.com/questions/4793604/how-to-insert-an-element-after-another-element-in-javascript-without-using-a-lib

6
4
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
6
4