LoginSignup
0
0

More than 1 year has passed since last update.

HTML要素を新たに追加するinsertBeforeの使い方~備忘録~

Posted at

子要素がHTML要素を持つ場合

以下のような構造のHTMLがあるとします。

<div id='text'>
  <p id='p1'>テキスト1</p>
  <p id='p2'>テキスト2</p>
  <p id='p3'>テキスト3</p>
</div>

テキスト1の後に、新しい要素

<p id='new'>新しいテキスト</p>

を追加したいとき。

const textElement = document.getElementById('text') // 親要素の取得
const p1Element = document.getElementById('p1') // 基準とする要素の取得

const newElement = document.createElement('p') // 追加要素
newElement.id = 'new' // id属性
newElement.textContent = "新しいテキスト" //テキスト

textElement.insertBefore(newElement, p1Element)

子要素がHTML要素を持たない場合

こんな状況あるのかな、、、
例えば、contenteditableな要素を操作する時に使えるのではないでしょうか。

以下のような構造のHTMLがあるとします。

<div contenteditable='true' id='text'>
 insertBeforeの使い方
</div>

Enterキーを押した時に、

<span style='color: red;'>Enterキーを押さないでください</span>

という要素を入力したテキストの後に追加したいとき。

const textElement = document.getElementById('text') //親要素の取得

const newAlertElement = document.createElement('span') // 新しい追加したい要素
newAlertElement.style.color = 'red' // 文字色を赤にする
newAlertElement.textContent = "Enterキーを押さないでください" // テキスト

textElement.insertBefore(newAlertElement, textElement.childNodes[0])

textElement.childNodes[0]というのは親要素の下にある"insertBeforeの使い方"を指します。

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