javascript insertAdjacentHTMLを使用してhtml要素を挿入する

javascript insertAdjacentHTMLを使用してhtml要素を挿入する

javascriptで、insertAdjacentHTMLを使用して、html要素を特定の場所に挿入するサンプルコードを記述してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.81

insertAdjacentHTML使い方

insertAdjacentHTMLを使用することで、特定の場所にhtmlを挿入するが可能です。

<div id="hoge" class="foo"><p>p要素</p></div>

<script>

'use strict';

document.getElementById('hoge').insertAdjacentHTML('beforebegin', '<h1>beforebegin</h1>');
document.getElementById('hoge').insertAdjacentHTML('afterbegin', '<h1>afterbegin</h1>');
document.getElementById('hoge').insertAdjacentHTML('beforeend', '<h1>beforeend</h1>');
document.getElementById('hoge').insertAdjacentHTML('afterend', '<h1>afterend</h1>');

</script>

実行結果

第一引数の種類は、挿入する要素の場所となり、以下の通り4つ存在します。

beforebegin : 指定した要素のタグの上に挿入します。
afterbegin : 指定した要素のタグの中の初めに挿入します。
beforeend : 指定した要素のタグの中の最後に挿入します。
afterend : 指定した要素のタグの下に挿入します。

タグと位置で表現すると、以下のようになります。

<!-- beforebegin -->
<parent>
    <!-- afterbegin -->
    <child>Text</child>
    <!-- beforeend -->
</parent>
<!-- afterend -->

存在しない要素

存在しない要素を指定すると、エラーとなります。

<div id="hoge" class="foo"><p>p要素</p></div>

<script>

'use strict';

document.getElementById('noelm').insertAdjacentHTML('beforebegin', '<h1>beforebegin</h1>');
// Uncaught TypeError: Cannot read properties of null (reading 'insertAdjacentHTML')

</script>

エラーを回避するには、存在チェックを行います。

<div id="hoge" class="foo"><p>p要素</p></div>

<script>

'use strict';

if( document.getElementById('noelm') !== null ){

    document.getElementById('noelm').insertAdjacentHTML('beforebegin', '<h1>beforebegin</h1>');

}

</script>

サンプルコード

以下は、
「実行」ボタンをクリックすると、指定した要素を挿入して表示する
サンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

const hoge = () => {

  add.insertAdjacentHTML( // document.getElementById('add');を省略   
    'beforebegin',
    '<h1><p class="bg-teal-500 text-white py-4 px-8 rounded-full mb-3 mt-4">追加されました</p></h1>'
  );

}

window.onload = () => {
  // クリックイベントを登録
  btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略    
}

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div id="add" class="flex justify-center">
    </div>

    <div class="flex justify-center">
      <button id="btn" type="button"
        class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
        実行
      </button>
    </div>
  </div>

</body>

</html>

要素が追加されていることが確認できます。