Element: insertAdjacentText() メソッド
        
        
          
                Baseline
                
                  Widely available
                
                
              
        
        
        
          
                
              
                
              
                
              
        
        
      
      This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2018年4月.
insertAdjacentText() は Element インターフェイスのメソッドで、与えられたテキストノードを、メソッドを実行した要素に対する相対的な位置に挿入します。
構文
js
insertAdjacentText(where, data)
引数
返値
なし (undefined)。
例外
- SyntaxError- DOMException
- 
whereが理解できない値である場合に発生します。
位置名の図解
html
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->
メモ:
beforebegin および afterend の位置が使えるのは、対象ノードがツリーの中にあって、親要素を持つ時に限られます。
例
js
beforeBtn.addEventListener("click", () => {
  para.insertAdjacentText("afterbegin", textInput.value);
});
afterBtn.addEventListener("click", () => {
  para.insertAdjacentText("beforeend", textInput.value);
});
GitHub 上にあるデモ insertAdjacentText.html を見てください。(同時にソースコードも読んでください。)ここにはシンプルな段落が 1 つあります。フォーム要素に好きなテキストを入力してから、Insert before または Insert after ボタンを押すと、insertAdjacentText() が、入力したテキストを段落のテキストの前または後に挿入します。すでにあるテキストノードにテキストが追加されるのではなく、新しい追加テキストが含まれる別のテキストノードが生成されて、それが追加されることに注意してください。
仕様書
| Specification | 
|---|
| DOM> # dom-element-insertadjacenttext> | 
ブラウザーの互換性
Loading…