javascript beforeで直前のノードにテキストや要素を追加する
- 2021.02.06
- javascript
- javascript

javascriptで、beforeを使用して、直前のノードにテキストや要素を追加するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
before使い方
beforeを使用すると、直前のノードにテキストや要素を追加することが可能です。
1 |
ノード.before |
before使い方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/* html */ <div id="main"> <div id="one">one</div> <div id="two">two</div> </div> /* javascript */ 'use strict'; const node1 = document.getElementById("one"); const node2 = document.getElementById("two"); // テキストを追加 node1.before("値を挿入"); // 要素を追加 const p = document.createElement("p"); node2.before(p); |
実行結果を見ると、テキストと要素が追加されているが確認できます。

テキストと要素を同時に追加することも可能です。
1 2 |
const p = document.createElement("p"); node2.before(p,"値を追加"); |
また、以下のコードを、
1 2 3 |
const node1 = document.getElementById("one"); node1.before("値を挿入"); |
document.getElementByIdの省略を使用して、簡潔に記述することもできます。
1 |
one.before("値を挿入"); |
サンプルコード
以下は、
「追加」ボタンをクリックして、テキストを追加して表示するだけの
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> </head> <script> window.onload = () => { btn.onclick = () => { sample.before("テキストを追加しました"); }; } </script> <body> <div class="container mx-auto my-56 w-64 px-4"> <div id="sample" class="flex flex-col justify-center"> <button id="btn" class="bg-gradient-to-r from-purple-400 to-purple-700 hover:from-pink-500 hover:to-yellow-500 text-white py-2 px-4 rounded-full mb-3 mt-4"> 追加 </button> </div> </div> </body> </html> |
追加されていることが確認できます。

-
前の記事
python 存在するフォルダやファイルの一覧を取得する 2021.02.06
-
次の記事
nuget 「リモート名を解決できませんでした。: ‘api.nuget.org’」が発生した場合 2021.02.07
コメントを書く