javascript html内に動的にコメントを追加する
- 2021.01.05
- javascript
- javascript

javascriptで、createCommentを使用して、html内に動的にコメントを追加するサンプルコードを掲載してます。ブラウザはchromeのデバックモードを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
createComment使い方
createCommentを使用すると、html内に動的にコメントを追加することが可能です。
1 |
const node = document.createComment("コメントを記述"); |
createComment使い方
1 2 3 4 5 6 7 8 9 10 11 |
/* html */ <body id="wrap"> </body> /* javascript */ 'use strict'; const node = document.createComment("コメントを追加"); document.body.appendChild(node); |
実行結果は、html内にコメントがされていることが確認できます。

macのsafari(13.1.3)でも同じ結果となります。

また、document.getElementByIdを省略して、簡潔に記述することもできます。
1 2 |
const node = document.createComment("コメントを追加"); wrap.appendChild(node); |
サンプルコード
以下は、
「コメント追加」をクリックするとコメントをhtml要素内に追加する
サンプルコードとなります。
※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 36 37 38 39 40 41 42 |
<!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> const hoge = () => { const node = document.createComment("コメントを追加"); sample.appendChild(node); } window.onload = () => { add.onclick = () => { hoge() }; } </script> <body> <div class="container mx-auto my-56 w-64 px-4"> <div id="sample" class="flex flex-col justify-center"> <button id="add" class="bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 text-white py-2 px-4 rounded-full mb-3 mt-4"> コメント追加 </button> </div> </div> </body> </html> |
コメントが追加されていることが確認できます。

-
前の記事
Ruby 配列を並び替え(ソート)をする 2021.01.05
-
次の記事
Vue3 ライブラリ「smart-tagz」を使用してタグ入力を実装する 2021.01.05
コメントを書く